当输出足够小时,给Snprintf()尺寸太大

发布于 2025-01-22 20:05:34 字数 244 浏览 1 评论 0原文

此代码会导致不确定的行为吗?因为缓冲区只有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花海 2025-01-29 20:05:34

C 2018 7.21.6.5 2说:

snprintf函数等于fprintf,只是将输出写入数组(由参数s指定)而不是将流。如果n为零,则没有写任何书面,而s可能是一个空指针。否则,输出字符以外的n-1 st 被丢弃而不是写入数组,并且在实际写入的字符的末尾写了一个空字符数组。

请注意,这不说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:

The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array.

Note this does not say snprintf is passed an array of n or more characters. So snprintf is not given any license to assume it may write to s[n-1] unless the fprintf that it is equivalent to would write n 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 call snprintf(buffer,294201,"%s","ABC");. Would we expect nothing beyond the first four characters to change? If some other byte in the buffer changed, then this snprintf call would not be “equivalent to fprintf, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文