简体   繁体   中英

Segmentation fault only when I redirect stdout to /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!

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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM