仅在打印时出现段错误

发布于 2024-12-28 00:59:54 字数 401 浏览 1 评论 0原文

我有一个循环,看起来像这样

while(condition){
  read_some_data(source, buf, BUFSIZE);
  printf(buf);
  memset(buf, 0, BUFSIZE+1);
  //do stuff to affect condition that does not touch buf
}

buf 是一个大小为 BUFSIZE+1 的字符数组。奇怪的是,如果我注释掉 printf,程序就会完美执行,没有分段错误。只有当我尝试打印 buf 时,我才遇到问题。此外,段错误不一定发生在循环的第一次迭代上。通常需要 6 或 7 次迭代。

此外,该程序中没有动态内存分配。

I have a loop that looks something like this

while(condition){
  read_some_data(source, buf, BUFSIZE);
  printf(buf);
  memset(buf, 0, BUFSIZE+1);
  //do stuff to affect condition that does not touch buf
}

buf is an char array of size BUFSIZE+1. The strange thing is that if I comment out the printf, the program executes perfectly with no segmentation fault. It is only when I try to print out buf that I get the problem. Also, the seg fault does not necessarily happen on the first iteration of the loop. It usually takes 6 or 7 iterations.

Also, there is no dynamic memory allocation in this program.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

月朦胧 2025-01-04 00:59:55
  • 确保 buf 在分配范围内的某个位置有一个空(零值)字节。 printf 可以通过该空字节判断它已到达字符串的末尾;如果没有它,它将继续阅读可以安全地阅读的地方。
  • 确保 buf 不包含 %dprintf 可能用来指示其他参数的内容。更好的是,只需使用 printf("%s", buf),即可完全消除任何此类风险。
  • Make sure that buf has a null (zero-valued) byte somewhere within the allocated range. That null byte is how printf can tell that it's reached the end of a string; without it, it will keep reading past where it can safely do so.
  • Make sure that buf doesn't contain anything like %d that printf might take to indicate additional arguments. Better yet — just use printf("%s", buf), which completely eliminates any such risk.
只想待在家 2025-01-04 00:59:55

您缺少 printf 的格式说明符参数

You are missing the format specifier argument to printf

画尸师 2025-01-04 00:59:55

确保 buf 是以 \0 结尾的字符串。
只有这样 printf() 才能打印字符串。

Make sure buf is \0 terminated string.
Only then printf() could print the string.

神也荒唐 2025-01-04 00:59:55

您需要将字符串指定为打印参数:printf("%s", buf);

希望这有帮助!

NS

You need to specify the string as a print parameter: printf("%s", buf);.

Hope this helps!

N.S.

檐上三寸雪 2025-01-04 00:59:55

它是以空终止的吗?如果您只想将 buf 写到标准输出,为什么要调用 printf(buf) 而不是 puts(buf) 呢?

Is it null-terminated? And why are you calling printf(buf) rather than puts(buf) if all you want to do is to write out the buf to stdout?

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