仅在打印时出现段错误
我有一个循环,看起来像这样
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
buf
在分配范围内的某个位置有一个空(零值)字节。printf
可以通过该空字节判断它已到达字符串的末尾;如果没有它,它将继续阅读可以安全地阅读的地方。buf
不包含%d
等printf
可能用来指示其他参数的内容。更好的是,只需使用printf("%s", buf)
,即可完全消除任何此类风险。buf
has a null (zero-valued) byte somewhere within the allocated range. That null byte is howprintf
can tell that it's reached the end of a string; without it, it will keep reading past where it can safely do so.buf
doesn't contain anything like%d
thatprintf
might take to indicate additional arguments. Better yet — just useprintf("%s", buf)
, which completely eliminates any such risk.您缺少 printf 的格式说明符参数
You are missing the format specifier argument to printf
确保
buf
是以\0
结尾的字符串。只有这样
printf()
才能打印字符串。Make sure
buf
is\0
terminated string.Only then
printf()
could print the string.您需要将字符串指定为打印参数:
printf("%s", buf);
。希望这有帮助!
NS
You need to specify the string as a print parameter:
printf("%s", buf);
.Hope this helps!
N.S.
它是以空终止的吗?如果您只想将 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?