The two expressions you gave are not equivalent:
sprintf takes no argument specifying the maximum number of bytes to write; it simply takes a destination buffer, a format string, and a bunch of arguments. Therefore, it may write more bytes than your buffer has space for, and in so doing write arbitrary code. The
%.*s is not a satisfactory solution because:
- When the format specifier refers to length, it’s referring to the equivalent of
strlen; this is a measure of the number of characters in the string, not its length in memory (i.e. it doesn’t count the null terminator).
- Any change in the format string (adding a newline, for example) will change the behavior of the
sprintfversion with respect to buffer overflows. With
snprintf, a fixed, clear maximum is set regardless of changes in the format string or input types.