Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

c - Is snprintf() ALWAYS null terminating?

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] = '';
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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...