I have observed that sometimes in C programs, if we have a printf in code anywhere before a segmentation fault, it does not print. Why is this so?
-
I frequently see non-native English speakers use the phrase "I have a doubt about...". I would hate to see native English speakers start using that improper use of the word "doubt".Rob– Rob2010-02-16 03:44:17 +00:00Commented Feb 16, 2010 at 3:44
6 Answers
It's because the output from printf() is buffered. You could add fflush(stdout); immediately after your printf and it would print.
Also you could do this:
fprintf(stderr, "error string");
since stderr is not buffered.
Comments
Most libc implementations buffer printf output. It's usually sufficient to append newline (\n) to the output string to force it to flush the buffers contents.
3 Comments
Random tip: if you're trying to debug segmentation faults, be sure to try valgrind. It makes it much easier!
Comments
You've been given a number of answers pointing out buffering of the output stream.
For better or worse, that's nowhere close to the only possibility though. A segmentation fault means the OS has detected that you've done something wrong, typically written outside out allocated memory. For better or worse (mostly worse) doing almost anything in such a situation can change enough of what the program does internally to prevent the problem from being detected, at least at the time/in the situation where it was detected previously.
For example, the segment fault may have been caused by writing through an uninitialized pointer -- that happened to hold a certain value (perhaps some small integer) because a function you'd called previously left that value at the right spot on the stack that when the later function was called, and used that same value as a pointer, it (reasonably dependably) contained a value the OS detected as a place you weren't allowed to write. Putting in a call to printf, however, might mean you're leaving some entirely different value at the spot on the stack that you're using without initialization. You're still writing somewhere you shouldn't, but it might now be somewhere that the OS doesn't know you shouldn't be writing.