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.
As the other answers establish: It should:
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 calledhistorically only had a function calledsnprintfbut instead_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
Visual Studio 2015 (VC14) apparently introduced the conforming
snprintffunction, but the legacy one with the leading underscore and the non null-terminating behavior is still there: