Is snprintf() ALWAYS null terminating?

As the other answers establish: It should:

snprintf … Writes the results to a character string buffer. (…)
will be terminated with a null character, unless buf_size is zero.

So all you have to take care is that you don’t pass an zero-size buffer to it, because (obviously) it cannot write a zero to “nowhere”.


However, beware that Microsoft’s library does not have a function called snprintf but instead historically only had a function called _snprintf (note leading underscore) which does not append a terminating null. Here’s the docs (VS 2012, ~~ VS 2013):

http://msdn.microsoft.com/en-us/library/2ts7cx93%28v=vs.110%29.aspx

Return Value

Let len be the length of the formatted data string (not including the
terminating null). len and count are in bytes for _snprintf, wide
characters for _snwprintf.

  • If len < count, then len characters are stored in buffer, a
    null-terminator is appended, and len is returned.

  • If len = count, then len characters are stored in buffer, no
    null-terminator is appended, and len is returned.

  • If len > count, then count characters are stored in buffer, no
    null-terminator is appended, and a negative value is returned.

(…)

Visual Studio 2015 (VC14) apparently introduced the conforming snprintf function, but the legacy one with the leading underscore and the non null-terminating behavior is still there:

The snprintf function truncates the output when len is greater
than or equal to count, by placing a null-terminator at
buffer[count-1]. (…)

For all functions other than snprintf, if len = count, len
characters are stored in buffer, no null-terminator is appended,
(…)

Leave a Comment