As @curiouskiwi stated, the "right" answer would be: you're padding your string to contain 3
sprintf() adds a
\0 char, so total is
4, but your
buffer is only
3 bytes long. Undefined behaviour is to be expected. You should always declare your buffers to contain enough chars for your strings.
Now, just for the sake of discussion, try following code:
* Testing 'sprintf()'
// char filename; // -> works OK
char filename; // "shouldn't" work. Nonetheless...
int i = 0;
while (i < 100)
sprintf(filename, "%05d", i);
printf("filename = %s\n", filename);
// Check addresses:
printf("&filename = %p\n", filename + 0);
printf("&filename = %p\n", filename + 1);
printf("&filename = %p\n", filename + 2);
printf("&i = %p\n", &i);
printf("DIFF &i - &filename = %ld bytes\n", (char*)&i - (filename + 2));
you'll (probably) get an output like:
filename = 00001
filename = 00002
filename = 00098
filename = 00099
filename = 00100
&filename = 0x7fff008bb500
&filename = 0x7fff008bb501
&filename = 0x7fff008bb502
&i = 0x7fff008bb50c
DIFF &i - &filename = 10 bytes
As you can see, you actually can (sometimes) step out of your buffer bounds and, if by little (and if a little lucky), you may not get any errors. This chunk of code just works!.
Of course, this doesn't mean this is correct: it just means it's a more subtle bug, which will be way more difficult to find, because your compiler won't yell back.
On the other hand, if you happened to pad your output with more zeros in a way you actually overwrite
i (remember we just saw, in the output, that
10 bytes away from
sprintf(filename, "%012d", i);
Your code would compile, but when you actually run it, you'd get yourself into an infinite loop.
Can see why? Every time through the loop,
i gets incremented, but then
sprintf overwrites it with zeros. Nonetheless
i is always pointing at the same mem location, so when you repeat the loop and try to increment it, the current value of
i is always
0, therefore the incremented value is always
Of course, the infinite loop doesn't happen in your code because your
while condition is independant of
jpg_number. But I'm pretty confident you'll find in a situation like this one if you run your code through
gdb (that's why my previous comment to your question).