From ISO C11 draft n1570:
The sprintf
function returns the number of characters written in the array,
not counting the terminating null character, or a negative value if an
encoding error occurred.
In other words, the return value of
sprintf(myString, "%d", 1023);
is indeed 4, but it actually writes 5 characters to myString
. More is revealed with snprintf
, which limits the number of characters written to the specified value, and this number should account for the terminating null character:
Thus, the null-terminated output has been completely written if and only
if the returned value is nonnegative and less than [the specified limit].
int avg_adc = 1023;
char myString[4];
int charsWritten;
charsWritten = snprintf(myString, sizeof(myString), "%d", avg_adc);
if (charsWritten >= 0 && charsWritten < sizeof(myString)) {
printf("OK :-)\n");
} else {
printf("TROUBLE :-(\n");
printf("Returned: %d\n", charsWritten);
printf("myString=%s, expected %d\n", myString, avg_adc);
}
Output on my system:
TROUBLE :-(
Returned: 4
myString=102, expected 1023
In other words, you need to check the return value of snprintf
. If the test fails, then your result string was truncated, and it needs to be one character larger than the return value to fit all of the characters that you want it to store, assuming a negative value isn't returned. Declaring char myString[5];
results in the following output:
OK :-)