PostHeaderIcon flush debugging

Sometimes buffering of output can lead to unexpected results, the code below is an example:

void do_stuff()
std::cout<<”Hello do_stuff”<<std::endl;
int main(int argc, char const *argv[])
/* code */
std::cout<<”Doing unrelated stuff”<<std::endl;
std::cout<<”Doing divide…”;
int i=0;
return 0;

When runs this program prints(on some systems):

Doing unrelated stuff
Hello do_stuff
Floating point exception

This problem is that output is being buffered, so the string “Doing divide …” goes into the buffer, then the crashes with a -Wdiv-by-zero exception,this is where the confusion comes from.

We can deal this situation with std::flush.

one way of doing this is to explicitly flush every statement when debugging:

you have to do the flush for every output statement.
std::cout<<”Doing divide…”<<std::flush;

In this way, you have to remember to do the flush for every statement.

The other way is to set unitbuf flag which tells C++ to flush after every output operation,just do once at the top of your program:

just do once

Being aware of what’s going inside the program is very useful to a programmer,knowing how to get around the internal limitations of the system is the mark of a good programmer.


Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2010 - C++ Technology. All Rights Reserved.

Powered by Jerry | Free Space Provided by