当输出足够小时,给Snprintf()尺寸太大
此代码会导致不确定的行为吗?因为缓冲区只有128个字节,但我告诉snprintf()
它的时间更长。但是,所得的字符串比128个字节短。
#include <stdio.h>
int main(void)
{
char buffer[128];
snprintf(buffer,294201,"%s","ABC");
puts(buffer);
return 0;
}
Does this code cause undefined behaviour? Because the buffer is only 128 byte long but i tell snprintf()
that it is longer. However, the resulting string is shorter than 128 byte.
#include <stdio.h>
int main(void)
{
char buffer[128];
snprintf(buffer,294201,"%s","ABC");
puts(buffer);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C 2018 7.21.6.5 2说:
请注意,这不说
snprintf
传递了n
或更多字符的数组。因此,snprintf
没有任何许可证可以假定它可以写入s [n-1]
,除非fprintf
等同于写作n
字符(包括终止空字符)。换句话说,假设我们定义一个数组
缓冲区
294,201个字符,用数据填充它,然后调用snprintf(buffer,294201,“%s”,“ abc”); <<< /代码>。除了前四个字符之外,我们会期望什么都不会改变吗?如果缓冲区中的其他一些字节更改,则此
snprintf
调用将不等于fprintf
,只是将输出写入数组中……”如果该规范在缓冲区中更改了任何内容,则违反了该规范。C 2018 7.21.6.5 2 says:
Note this does not say
snprintf
is passed an array ofn
or more characters. Sosnprintf
is not given any license to assume it may write tos[n-1]
unless thefprintf
that it is equivalent to would writen
characters (including the terminating null character).Looking at this another way, suppose we define an array
buffer
of 294,201 characters, fill it with data, and callsnprintf(buffer,294201,"%s","ABC");
. Would we expect nothing beyond the first four characters to change? If some other byte in the buffer changed, then thissnprintf
call would not be “equivalent tofprintf
, except that the output is written into an array…” I would deem it a violation of this specification if it changed anything further in the buffer.