Last Updated: February 25, 2016
·
496
· coldgrnd

printf behavior in C/C++

reasoning about the program behavior can be tricky at times. printf often is very handy to get some kind of a trace of what happens.

What I didn't know for a long time is that the stdout stream is buffered!

That means your program might terminate before all the output is printed.

One workaround I heard from John Hinke (from ESRLabs) : use fprintf and configure it with stderr.

fprintf(stderr, "fuck yeah!");

What I ended up with is disabling the buffering of stdout:

setbuf(stdout, 0);

from the docs:

Specifies the buffer to be used by the stream for I/O operations, which becomes a fully buffered stream. Or, alternatively, if buffer is a null pointer, buffering is disabled for the stream, which becomes an unbuffered stream.