I'm cognizant of using snprintf()
in lieu of sprintf()
for safety. However, I always do memset()
on buffer used by snprintf()
. I saw some codes using the function without memset()
. And, it works as expected. I mean there is no overwriting on the buffer. Let me exemplify,
char str[100];
snprintf(str, sizeof(str), "stackoverflow %zu", sizeof(str));
fprintf(stderr, "%s\n", str);
snprintf(str, sizeof(str), "soner");
fprintf(stderr, "%s\n", str);
Until now, I thought that the code would print soneroverflow 100
that's why I used memset()
. Nevertheless, it prints soner
. How is it done underhood? By the way, same thing is applied for sprintf()
.
From snprintf:
A terminating null character is automatically appended after the content written.
If you were to inspect the buffer, you would find
{ 's', 'o', 'n', 'e', 'r', '\0', 'v', 'e', 'r', /* ... */ }