是的snprintf()总是空终止? [英] Is snprintf() ALWAYS null terminating?

查看:300
本文介绍了是的snprintf()总是空终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总是snprintf的空终止目标缓冲区?

Is snprintf always null terminating the destination buffer?

在换句话说,这是足够了:

In other words, is this sufficient:

char dst[10];

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

或做你必须做的就是这样,如果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);

我无论在什么标准说什么一些流行的libc可能会做这是不规范的行为感兴趣。

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:

的snprintf ......结果写入字符串缓冲区。 (......)
  将与空字符终止,除非buf_size为零。

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".

然而,提防,微软的库<罢工>的没有的调用的函数的snprintf 而是历史的只有的已调用的函数 _snprintf (注意前导下划线),它的不追加的终止空。这里的文档(VS 2012,VS〜2013):

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 /库/ 2ts7cx93%28V = vs.110%29.aspx

让LEN是格式化的数据串的长度(不包括
  终止空)。 LEN和数量都在为_snprintf字节宽
  字符_snwprintf。

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.


      
  • 如果LEN&LT;算,然后len个字符被存储在缓冲区中,一个
      空终止符附加,并返回LEN。

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

如果len =计数,然后len个字符存储在缓冲区中,
  空终止符附加,并返回LEN。

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

如果LEN>计数,然后计算字符存储在缓冲区中,
  空终止符附加,并返回一个负值。

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)显然是推出了符合的snprintf 的功能,但是传统的一个具有领先的下划线和的的空终止的行为仍然存在:

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:

的snprintf 截断功能时的输出len为更大
  大于或等于算,通过放置一个空终止
  缓冲[计数1] 。 (...)

有关的所有功能的其他的比的snprintf ,如果len =计数,LEN
  字符存储在缓冲区的没有空终止附加的,
  (...)

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

这篇关于是的snprintf()总是空终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆