Consider the following code:
char buffer[5]{};
snprintf(buffer, sizeof(buffer), "hi");
snprintf
writes 'h'
, 'i'
and ''
to buffer
.
My question is: is there any guarantee that the snprintf
won’t touch buffer[3]
and buffer[4]
according to the standard? Visual Studio 2019 keeps the unused buffer untouched, but is this a standard behavior?
2
Answers
The N1548 draft ISO/IEC 9899:201x Programming languages — C
It clearly defines how much characters would be written. It does not guarantee that characters are not modified in the target buffer after the returned value + 1.
If you run your code in POSIX environment and if such the guarantee is a requirement, you can use a memory stream opened with
fmemopen()
and used withfprintf()
.fprintf()
guarantees that it will not modify characters after the terminating null character.I cannot think of a reason that it will alter content in the remaining space. But if you are worried about that, determine the length before calling snprintf() in the code like below.