仅当我将 stdout 重定向到 /dev/null 时才出现分段错误?
我有一个 C++ 单元测试,它向 stderr 生成有用的输出,并且向 stdout 生成大部分噪音(除非我正在调试),因此我想将 stdout 重定向到 /dev/null。
奇怪的是,这样做似乎会导致分段错误。
是否有任何原因导致代码可能会出现“> /dev/null”的分段错误,而其他情况下则可以正常运行?
如果有任何影响的话,输出完全由 printf 产生。
我很难发布有问题的代码,因为这是正在提交出版的研究。我希望根据此描述有一个“明显”的可能原因。
事后
分析 段错误是由这样的代码引起的:
ArrayElt* array = AllocateArrayOfSize(array_size);
int index = GetIndex(..) % array_size;
ArrayElt elt = array[index];
无数次,我忘记了当 x
在 C/C++ 中为负数时,x % y
仍然为负数。
好的,那么为什么只有当我重定向到 /dev/null
时才会发生这种情况?我的猜测是,我访问的无效内存地址位于标准输出的输出缓冲区中,并且在不需要时不会分配该缓冲区。
感谢您的好回答!
I've got a C++ unit test that produces useful output to stderr, and mostly noise (unless I'm debugging) to stdout, so I'd like to redirect the stdout to /dev/null.
Curiously enough, doing this seems to cause a segmentation fault.
Is there any reason why code might seg fault with "> /dev/null" and run fine otherwise?
The output is produced entirely by printf
s, if that has any bearing.
It is difficult for me to post the offending code because it is research being submitted for publication. I'm hoping there is an "obvious" possible cause based on this description.
post mortem
The segfault was being caused by code like this:
ArrayElt* array = AllocateArrayOfSize(array_size);
int index = GetIndex(..) % array_size;
ArrayElt elt = array[index];
For the umpteenth time, I forgot that x % y
remains negative when x
is negative in C/C++.
Ok, so why was it only happening when I redirected to /dev/null
? My guess is that the invalid memory address I was accessing was in an output buffer for stdout - and this buffer isn't allocated when it isn't needed.
Thanks for the good answers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这并不能完全回答你的问题,但它可以。您是否尝试过使用gdb?它是一个命令行调试工具,可以找到发生段错误的位置。它相当容易使用。 这里有一个关于如何使用它的非常深入的教程。
This doesn't exactly answer your question, but it could. Have you tried using gdb? It's a command-line debugging tool that can find where segfaults are occurring. It's fairly easy to use. Here is a pretty in-depth tutorial on how to use it.
当标准输出重定向到 /dev/null 时,stdout 的 I/O 没有“正常”原因触发核心转储。
您很可能有一个流浪指针或缓冲区溢出,当发送到 /dev/null 时触发核心转储,而不是发送到标准输出时触发核心转储 - 但如果没有代码,将很难发现问题。
按照惯例,将有用信息放在标准输出上,将噪声放在标准错误上。
There is no 'normal' reason for I/O to stdout to trigger a core dump when standard output is redirected to /dev/null.
You most probably have a stray pointer or a buffer overflow that triggers the core dump when sent to /dev/null and not when sent to standard output - but it will be hard to spot the problem without the code.
It is conventional to put the useful information on standard output and the noise on standard error.
可能是某些东西正在检查“isatty”,这可能会导致
/dev/null
出现不同的行为。可能是从标准输出读取某些内容,
/dev/null
会失败。It could be that something is checking "isatty", which might cause different behavior for
/dev/null
.It might be that something is reading from stdout, which would fail for
/dev/null
.