sprintf in C resets the value of counting variable

c, printf

Solution

`title` is too small, sprintf is writing beyond the bounds of `title`, and writing into `count`, corrupting its value.

Note that `title` needs to be long at least 8 bytes: 3 for `%.3d`, 4 for `.jpg` and 1 for the terminator `\0`.

As Grijesh Chauhan points out, you can make sure that you never write beyond the allocated size of the string by using `snprintf`, i.e.:

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

Problem

I'm having an issue with sprintf in C resetting the value of a counter variable when I run it. Here in a nutshell is what is happening: ``` 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?

Original source

Related problems