Does this code cause undefined behaviour? Because the buffer is only 128 byte long but i tell snprintf()
that it is longer. However, the resulting string is shorter than 128 byte.
#include <stdio.h>
int main(void)
{
char buffer[128];
snprintf(buffer,294201,"%s","ABC");
puts(buffer);
return 0;
}
C 2018 7.21.6.5 2 says:
The
snprintf
function is equivalent tofprintf
, except that the output is written into an array (specified by arguments
) rather than to a stream. Ifn
is zero, nothing is written, ands
may be a null pointer. Otherwise, output characters beyond then-1
st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array.
Note this does not say snprintf
is passed an array of n
or more characters. So snprintf
is not given any license to assume it may write to s[n-1]
unless the fprintf
that it is equivalent to would write n
characters (including the terminating null character).
Looking at this another way, suppose we define an array buffer
of 294,201 characters, fill it with data, and call snprintf(buffer,294201,"%s","ABC");
. Would we expect nothing beyond the first four characters to change? If some other byte in the buffer changed, then this snprintf
call would not be “equivalent to fprintf
, except that the output is written into an array…” I would deem it a violation of this specification if it changed anything further in the buffer.