Sprintf in C resets count variable value

I am having a problem with sprintf in C when I run its value for a counter variable. Here in a nutshell, what happens is:

int count = 0; count++; printf("%d\n", count); // count will equal 1 char title[7]; sprintf(title, "%.3d.jpg", count); printf("%d\n", count); // count now equals 0 again 

Is this normal behavior for sprintf?

+6
source share
3 answers

title too small, sprintf writes beyond title and writes to count , distorting its value.

Please note that title must be at least 8 bytes long: 3 for %.3d , 4 for .jpg and 1 for terminator \0 .

As Grijesh Chauhan points out, you can make sure that you never write outside of the allocated row size using snprintf , ie:

 char title[8]; snprintf(title, sizeof(title), "%.3d.jpg", count); 
+12
source

You just need more space in the line header: 3 digits + ". Jpg" = 7 characters, and you need one extra for '\ 0' (end of line). Sprintf may change the argument in this case ( Using sprintf will change the specified variable )

Solution: change

char title [7];

to

char title [8];

0
source

The problem is called buffer overflow . sprintf has no idea about the size of the title , and the entry has as much as needed, even if it exceeds the bounds of your array. To fully understand, you should also know that strings end with zero. This allows you to find the end of a line without first knowing its true size. This extra zero replaces the extra character that you should consider when sizing buffers.

Consider also using snprintf , which ensures that you do not go beyond the boundaries of your buffer.

0
source

All Articles