-1

My question is general and doesn't relate to a specific debugging scenario.

When a program terminate unexpectedly (panic, memory corruption, access violation etc... ) , sometimes the recent stdout messages doesn't appear on the screen, even though they occurred prior to the termination.

That's because stdout messages are first being written to buffer that is also erased upon termination without being written to stdout in advance.

My question is whether there's a generic option to flush all debug messages in c/c++ code before program terminate unexpectedly ? (I would prefer using some generic compiler configuration rather that an ad-hoc solution for a specific implementation such as std::cout - if there's such option, I'd be happy to know if it's common to GCC and G++)

Note : I assume that when flushing this buffer for each new arriving message, will damage performance. however, it's only meant for debug version.

thanks

Zohar81
  • 4,554
  • 5
  • 29
  • 82
  • 2
    You should find out where it crashes with a debugger. – Jabberwocky Aug 05 '15 at 11:26
  • 5
    Try `fflush(stdout);`. However, you may want to debug with a debugger instead of printing variable values. – Banex Aug 05 '15 at 11:26
  • 2
    a generic suggestion, if in C, try to add a `\n` at the end of the format string in printf – Sourav Ghosh Aug 05 '15 at 11:26
  • 2
    This is what `stderr` is for. – sbi Aug 05 '15 at 11:30
  • 2
    `setvbuf()` allows you to set the `mode` to unbuffered. – EOF Aug 05 '15 at 11:31
  • 1
    If, despite the previous suggestions, you really want to disable buffering you can do so with [`setvbuf`](http://en.cppreference.com/w/c/io/setvbuf) – Kninnug Aug 05 '15 at 11:31
  • Realise changing the buffer won't "avoid performance degradation", it could only make performance worse, although with human readable output you won't see a difference, realistically. – Veltas Aug 05 '15 at 11:36
  • 1
    Is this C or C++? they are not the same thing. – NathanOliver Aug 05 '15 at 11:59
  • I assumed there's no difference between c and c++... I'd be happy to know how to flush this buffer on both cases. some documentation references would also be appreciated. – Zohar81 Aug 05 '15 at 12:08
  • Please add a snippet of your code to make clear exactly what you're doing. –  Aug 05 '15 at 12:35
  • If you are using cout, use std::ostream::flush to flush the buffer. An small example would help. – Robert Jacobs Aug 05 '15 at 12:41
  • If `stdout` is to a terminal (as opposed to a pipe or file), it should be line-buffered by default. If you want to force line-buffered output, there are "fake TTY" wrapper programs out there, e.g. `socat` can do it. – o11c Aug 05 '15 at 21:13

1 Answers1

2

Try setvbuf to set no buffer

setvbuf(stream, NULL, _IONBF, 0)