8

When a segmentation fault occurs, the printf() before it does not execute.

main()
{
 printf( "something" );
 statement;  //this statement causes a segmentation fault
}

In the situation above, why does the printf() not execute?

So do I need to use valgrind in such a case(which prints all printf() before the faulty statement).

James
  • 2,454
  • 1
  • 22
  • 22
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222

3 Answers3

13

Make sure you include a newline "\n" in your printf statement. Normally, at least in UNIX systems, stdout is line-buffered so newline character makes the line to appear immediately. You probably omitted "\n" (or your output is not flushed for other reason) and that's why you can't see the printed string.

Another option is to flush the output yourself using fflush(stdout) after calling printf.

ecik
  • 819
  • 5
  • 11
11

An output stream can fail to be output before a program crash but you can force the bytes to be output by flushing them with fflush().

I usually do it with something like this:

if (trace) { fflush(stdout); }
Richard T
  • 4,570
  • 5
  • 37
  • 49
  • "trace" is anything special ..?? or u have just used to detect segmention fault.? – Jeegar Patel Aug 09 '11 at 18:22
  • 1
    @Mr.32 -- I took his ```trace``` to be a variable he set up during init, maybe from a command-line option. – Heath Hunnicutt Aug 09 '11 at 18:35
  • Alternately, `fprintf` to `stderr`. – David Thornley Aug 09 '11 at 20:01
  • @DavidThornley No, while sending to stderr is a nice thing to do, it would still get caught up and _possibly_ not sent out; what flush does is tell the system to flush the pending writes - get em done! So, fprintf to stderr would have the same behavior as the previous call. – Richard T Mar 15 '12 at 16:11
  • `stderr` is unbuffered by default, even if redirected to a file. It never needs manual flushing after any IO call on it. – Peter Cordes Dec 31 '21 at 07:43
2

Output via printf() and any other standard I/O function is buffered in the standard C library.

You need to call fflush() to ensure the output is sent to the tty before your program crashes.

Heath Hunnicutt
  • 18,667
  • 3
  • 39
  • 62