Sprintf overwrites argument!

less than 1 minute read

A relatively easy one line of code, but doesn’t work properly.

sprintf(target\_str, "write %s", copied\_str);

Somehow, copied_str is changing. I tried making it const but no luck, still changing. Then I realized target\_str is not big enough for overall string. That’s why it was overwriting because target\_str and copied\_str are defined in a row! So which means their addresses are sequential. I increased the size of target\_str, and problem solved.

Moral of the story, never be mean about string lengths.

Categories:

Updated:

Leave a Comment