5

I don't understand why sometimes I need to use fflush() and sometimes not.

My program is segfaulting at the moment and I am debugging it with print statements. When a program segfaults, does stdout not flush its buffer automatically?

darksky
  • 20,411
  • 61
  • 165
  • 254
  • 1
    `stdout` is just a pointer, it doesn't "do" anything by itself. The real question would be, "doesn't the OS flush all open files?" – Kerrek SB Nov 29 '11 at 19:10

3 Answers3

9

I don't understand why sometimes I need to use fflush() and sometimes not.

Sometimes the stdio buffers are flushed sometimes they aren't. For example simply including a "\n" in the printed stuff will typically flush it (because stdout is by default line-buffered when attached to a terminal).

When a program segfaults, does stdout not flush its buffer automatically ?

Stdio buffers are flushed by exit. When a signal (such as SIGSEGV) kills a process, exit is not called. Another way to exit a process without flushing the stdio buffers is to use the Unix-specific call _exit.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
1

No, why should it. The program gets killed by the operating system. If a segfault occurs, the program is no longer in a meaningful state, so nothing can safely happen at that point other than immediate termination.

(And don't nobody try to register a signal handler for SIGSEGV.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • In some cases, registering a signal handler for `SIGSEGV` is valid - for instance if you're making a read-only mapping with `mmap`, you can catch and `longjmp` out of write attempts on it with a signal handler, and this is 100% (as far as POSIX is concerned) portable and valid as long as the write was not being performed by an async-signal-unsafe function. – R.. GitHub STOP HELPING ICE Nov 29 '11 at 23:39
  • 1
    @R..: as usual with "pseudo-advice": once you understand when it's safe to ignore, you can safely ignore it ;-) In any event, you must terminate the program eventually; you cannot recover from the signal. – Kerrek SB Nov 29 '11 at 23:40
0

"I cannot figure out why fflush (stdout) is called here in this code I try to comment this line and behavior was exactly the same."

Because you're not guaranteed to see previous printf() output if that output doesn't end in a newline.

Basically, you only need it if you're displaying say a prompt without a newline, and you want to make sure the user can see it.

See this site.

djhaskin987
  • 9,741
  • 4
  • 50
  • 86