gpt4 book ai didi

c - snprintf() 总是空终止吗?

转载 作者:太空狗 更新时间:2023-10-29 16:16:01 24 4
gpt4 key购买 nike

snprintf 总是以 null 终止目标缓冲区吗?

换句话说,这是否足够:

char dst[10];

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

如果 somestr 足够长,您是否必须这样做?

char dst[10];

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

我对标准所说的内容以及某些流行的 libc 可能执行的非标准行为都很感兴趣。

最佳答案

正如其他答案所确定的那样:它 should :

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

所以您需要注意的是不要将零大小的缓冲区传递给它,因为(显然)它不能将零写入“无处”。


但是,请注意微软的库 没有一个名为 snprintf 的函数,而是 历史上只有 有一个名为_snprintf 的函数(注意前导下划线),它不附加 终止空值。这是文档(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) 显然引入了符合要求的 snprintf 函数,但带有前导下划线和 空终止行为的遗留函数仍然存在:

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

关于c - snprintf() 总是空终止吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7706936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com