Is snprintf() ALWAYS null terminating?

CPosixLibc

C Problem Overview


Is snprintf always null terminating the destination buffer?

In other words, is this sufficient:

char dst[10];

snprintf(dst, sizeof (dst), "blah %s", somestr);

or do you have to do like this, if somestr is long enough?

char dst[10];

somestr[sizeof (dst) - 1] = '\0';
snprintf(dst, sizeof (dst) - 1, "blah %s", somestr);

I am interested both in what the standard says and what some popular libc might do which is not standard behavior.

C Solutions


Solution 1 - C

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, > (...)

Solution 2 - C

According to snprintf(3) manpage.

> The functions snprintf() and vsnprintf() write at most size bytes (including the trailing null byte ('\0')) to str.

So, yes, no need to terminate if size >= 1.

Solution 3 - C

According to the C standard, unless the buffer size is 0, vsnprintf() and snprintf() null terminates its output.

> The snprintf() function shall be equivalent to sprintf(), with the addition of the n argument which states the size of the buffer referred to by s. If n is zero, nothing shall be written and s may be a null pointer. Otherwise, output bytes beyond the n-1st shall be discarded instead of being written to the array, and a null byte is written at the end of the bytes actually written into the array.

So, if you need to know how big a buffer to allocate, use a size of zero, and you can then use a null pointer as the destination. Note that I linked to the POSIX pages, but these explicitly say that there is not intended to be any divergence between Standard C and POSIX where they cover the same ground:

> The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2008 defers to the ISO C standard.

Be wary of the Microsoft version of vsnprintf(). It definitely behaves differently from the standard C version when there is not enough space in the buffer (it returns -1 where the standard function returns the required length). It is not entirely clear that the Microsoft version null terminates its output under error conditions, whereas the standard C version does.

Note also the answers to Do you use the TR 24731 safe functions? (see MSDN for the Microsoft version of the vsprintf_s()) and Mac solution for the safe alternatives to unsafe C standard library functions?

Solution 4 - C

Some older versions of SunOS did weird things with snprintf and might have not NUL-terminated the output and had return values that didn't match what everyone else was doing, but anything that has been released in the past 10 years have been doing what C99 says.

Solution 5 - C

The ambiguity starts from the C Standard itself. Both C99 and C11 have identical description of snprintf function. Here is the description from C99:
> 7.19.6.5 The snprintf function
Synopsis
1 #include <stdio.h> int snprintf(char * restrict s, size_t n, const char * restrict format, ...);
Description
2 The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st 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. If copying takes place between objects that overlap, the behavior is undefined.
Returns
3 The snprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

On the one hand the sentence
> Otherwise, output characters beyond the n-1st 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

says that
if (the s points to a 3-character-long array, and) n is 3, then 2 characters will be written, and the characters beyond the 2nd one are discarded; then the null character is written after those 2 (and the null character will be the 3rd character written).

And this I believe answers the original question.
THE ANSWER:
If copying takes place between objects that overlap, the behavior is undefined.
If n is 0 then nothing is written to the output
otherwise, if no encoding errors encountered, the output is ALWAYS null-terminated (regardless of whether the output fits in the output array or not; if not then some characters are discarded such that the output array is never overflown),
otherwise (if encoding errors are encountered) the output can stay non-null-terminated.

On the other hand
The last sentence > Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n

gives ambiguity (or my English is not good enough). I can interpret this sentence in at least two ways:

  1. The output is null-terminated if and only if the returned value is nonnegative and less than n (which means that if the returned value is not less than n, i.e. the output (including the terminating null character) does not fit in the array, then the output is not null-terminated).
  2. The output is complete (no characters have been discarded) if and only if the returned value is nonnegative and less than n.

I believe that the interpretation 1 above contradicts THE ANSWER, causes misunderstanding and lengthy discussions. That is why the last sentence describing the snprintf function needs a change in order to remove any ambiguity (which gives grounds for writing a Proposal to the C language Standard).
The example of non-ambiguous wording I believe can be taken from http://en.cppreference.com/w/c/io/fprintf (see 4)), thanks to @"Martin Ba" for the link.

See also the question "snprintf: Are there any C Standard Proposals/plans to change the description of this func?".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionProf. FalkenView Question on Stackoverflow
Solution 1 - CMartin BaView Answer on Stackoverflow
Solution 2 - CpiotrView Answer on Stackoverflow
Solution 3 - CJonathan LefflerView Answer on Stackoverflow
Solution 4 - CArtView Answer on Stackoverflow
Solution 5 - CRobin KuzminView Answer on Stackoverflow