I'm working on a project where I call a function which triggers a segfault. I fixed this, but during the process I noticed the following.
When my code is of the format;
main(){
...
std::cout << "Looking for segfault\n"; // this does not print
buggyFunction(); // crashes in here
...
}
buggyFunction(){
...
thing_that_causes_segfault;
...
}
The line "Looking for segfault" doesn't print to STD, and the program crashes in buggyFunction. Fine, but when I add a cout line inside buggyFunction();
main(){
...
std::cout << "Looking for segfault\n"; // this now *does* print
buggyFunction();
...
}
buggyFunction(){
...
std::cout << "Now we're INSIDE buggy function\n"; // this prints too
thing_that_causes_segfault;
...
}
Inside buggy function, both lines print (and then it crashes).
Why do we see this difference in ouput, depending on the addition of this extra output call? Is it related to the handling of streams, or something else? I'm using g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3.
The reason for this is that cout has a buffer and it will only pass to the system function and write to the console when the buffer is full. Your second use of cout happens to overflow the buffer and so it calls the operating system and empties the buffer. If you want to guarantee that the output has left the buffer, you must use std::flush. You can both end a line and flush the buffer with std::endl.
Because your line might not immediately printed out because it's cached and the cache is not "flushed". std::endl is an newline + a flush thus forces immediate printout:
std::cout << "Looking for segfault" << std::endl;
It has to do with buffering. Things that you write to cout are appended to an internal buffer that only gets flushed periodically. You can explicitly flush the buffer by writing std::flush to your stream, or replacing the "\n" with << std::endl.
Related
Is there any circumstance when std::cout << "hello" doesn't work? I have a c/c++ code, however the std::cout doesn't print anything, not even constant strings (such as "hello").
Is there any way to check if cout is able/unable to open the stream? There are some member functions like good(), bad(), ... but I don't know which one is suitable for me.
Make sure you flush the stream. This is required because the output streams are buffered and you have no guarantee over when the buffer will be flushed unless you manually flush it yourself.
std::cout << "Hello" << std::endl;
std::endl will output a newline and flush the stream. Alternatively, std::flush will just do the flush. Flushing can also be done using the stream's member function:
std::cout.flush();
std::cout won't work on GUI apps!
Specific to MS Visual Studio:
When you want a console application and use MS Visual Studio, set project property "Linker -> System -> SubSystem" to Console. After creating a new Win32 project (for a native C++ app) in Visual Studio, this setting defaults to "Windows" which prevents std::cout from putting any output to the console.
To effectively disable buffering you can call this:
std::setvbuf(stdout, NULL, _IONBF, 0);
Alternatively, you can call your program and disable output buffering in the command line:
stdbuf -o 0 ./yourprogram --yourargs
Keep in mind this is not usually done for performance reasons.
It is probable that std::cout doesn't work due to buffering (what you're writing ends up in the buffer of std::cout instead of in the output).
You can do one of these things:
flush std::cout explicitly:
std::cout << "test" << std::flush; // std::flush is in <iostream>
std::cout << "test";
std::cout.flush(); // explicitly flush here
std::cout << "test" << std::endl; // endl sends newline char(s) and then flushes
use std::cerr instead. std::cerr is not buffered, but it uses a different stream (i.e. the second solution may not work for you if you're interested in more than "see message on console").
This question already has answers here:
endl and flushing the buffer
(5 answers)
Closed 6 years ago.
std::cout << "Enter two numbers:";
std::cout << std:endl;
This code snippet is followed by two paragraphs and a warning note, among which I understood the first para, but neither the second one nor the note. The text is as follows -
"The first output operator prints a message to the user. That message
is a string literal, which is a sequence of characters enclosed in
double quotation marks. The text between the quotation marks is
printed to the standard output.
The second operator prints endl,
which is a special value called a manipulator. Writing endl has
the effect of ending the current line and flushing the buffer
associated with that device. Flushing the buffer ensures that all the
output the program has generated so far is actually written to the
output stream, rather than sitting in memory waiting to be written.
Warning Programmers often add print statements during debugging. Such statement should always flush the stream. Otherwise, if the
program crashes, output may be left in the buffer, leading to
incorrect inferences about where the program crashed."
So I didn't understand of the part of endl, nor the following warning. Can anyone please explain this to me as explicitly as possible and please try to keep it simple.
Imagine you have some code that crashes somewhere, and you don't know where. So you insert some print statements to narrow the problem down:
std::cout << "Before everything\n";
f1();
std::cout << "f1 done, now running f2\n";
f2();
std::cout << "all done\n";
Assuming that the program crashes during the evaluation of either f1() or f2(), you may not see any output, or you may see partial output that is misleading -- e.g. you could see only "Before everything", even though the crash happened in f2(). That's because the output data may be waiting in a buffer and hasn't actually been written to the output device.
The Primer's recommendation is therefore to flush each output, which you can conveniently achieve with endl:
std::cout << "Before everything" << std::endl;
f1();
std::cout << "f1 done, now running f2" << std::endl;
f2();
std::cout << "all done" << std::endl;
An alternative is to write debug output to std::cerr instead, which is not buffered by default (though you can always change the buffering of any ostream object later).
A more realistic use case is when you want to print a progress bar in a loop. Usually, a newline (\n) causes line-based output to be printed anyway, but if you want to print a single character for progress, you may not see it printed at all until after all the work is done unless you flush:
for (int i = 0; i != N; ++i)
{
if (i % 1000 == 0)
{
std::cout << '#'; // progress marger
std::cout.flush();
}
do_work();
}
std::cout << '\n';
Well, simply:
std::cout << "Hello world!";
will print "Hello world!" and will remain in the same line. Now if you want to go to a new line, you should use:
std::cout << "\n";
or
std::cout << std::endl;
Now before I explain the difference, you have to know 1 more simple thing: When you issue a print command with the std::cout stream, things are not printed immediately. They are stored in a buffer, and at some point this buffer is flushed, either when the buffer is full, or when you force it to flush.
The first kind, \n, will not flush, but the second kind std::endl, will go to a new line + flush.
Operating systems do buffered IO. That is, when your program outputs something, they dont necessarily put it immediately where it should go (i.e. disk, or the terminal), they might decide to keep the data in an internal memory buffer for some while before performing the actual IO operation on the device.
They do this to optmize performance, because doing the IO in chunks is better than doing it immediately as soon as there are a few bytes to write.
Flushing a buffer means asking the OS to perform immediately the IO operation without any more waiting. A programmer would do this this when (s)he knows that waiting for more data doesn't make sense.
The second note says that endl not only prints a newline, but also hints the cout to flush its buffer.
The 3rd note warns that debugging errors, if buffered and not flushed immediately, might not be seen if the program crashes while the error messages are still in the buffer (not flushed yet).
I have code such as the following:
std::cout << "Beginning computations..."; // output 1
computations();
std::cout << " done!\n"; // output 2
The problem, however, is that often output #1 and output #2 appear (virtually) simultaneously. That is, often output #1 does not get printed to the screen until after computations() returns. Since the entire purpose of output #1 is to indicate that something is going on in the background (and thus to encourage patience from the user), this problem is not good.
Is there any way to force the std::cout buffer to get printed before the computations() call? Alternatively, is there some other way (using something other than std::cout) to print to standard out that would fix this problem?
Just insert std::flush:
std::cout << "Beginning computations..." << std::flush;
Also note that inserting std::endl will also flush after writing a newline.
In addition to Joseph Mansfield answer, std::endl does the flush too (besides a new line).
Inserts a endline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush().
Is there any circumstance when std::cout << "hello" doesn't work? I have a c/c++ code, however the std::cout doesn't print anything, not even constant strings (such as "hello").
Is there any way to check if cout is able/unable to open the stream? There are some member functions like good(), bad(), ... but I don't know which one is suitable for me.
Make sure you flush the stream. This is required because the output streams are buffered and you have no guarantee over when the buffer will be flushed unless you manually flush it yourself.
std::cout << "Hello" << std::endl;
std::endl will output a newline and flush the stream. Alternatively, std::flush will just do the flush. Flushing can also be done using the stream's member function:
std::cout.flush();
std::cout won't work on GUI apps!
Specific to MS Visual Studio:
When you want a console application and use MS Visual Studio, set project property "Linker -> System -> SubSystem" to Console. After creating a new Win32 project (for a native C++ app) in Visual Studio, this setting defaults to "Windows" which prevents std::cout from putting any output to the console.
To effectively disable buffering you can call this:
std::setvbuf(stdout, NULL, _IONBF, 0);
Alternatively, you can call your program and disable output buffering in the command line:
stdbuf -o 0 ./yourprogram --yourargs
Keep in mind this is not usually done for performance reasons.
It is probable that std::cout doesn't work due to buffering (what you're writing ends up in the buffer of std::cout instead of in the output).
You can do one of these things:
flush std::cout explicitly:
std::cout << "test" << std::flush; // std::flush is in <iostream>
std::cout << "test";
std::cout.flush(); // explicitly flush here
std::cout << "test" << std::endl; // endl sends newline char(s) and then flushes
use std::cerr instead. std::cerr is not buffered, but it uses a different stream (i.e. the second solution may not work for you if you're interested in more than "see message on console").
I am trying to print results in 2 nested for cycles using std::cout. However, the results are not printed to the console immediately, but with delay (after both for cycles or the program have been finished).
I do not consider such behavior normal, under Windows printing works OK. The program does not use threads.
Where could be the problem? (Ubuntu 10.10 + NetBeans 6.9).
std::cout is an stream, and it is buffered. You can flush it by several ways:
std::cout.flush();
std::cout << std::flush;
std::cout << std::endl; // same as: std::cout << "\n" << std::flush`
johny:
I am flushing the buffer before the cycle using std::endl. The problem arises when printing dot representing % of processed data inside the cycle.
If you flush the buffer before the cycle, that does not affect the output in the cycle. You have to flush in or after the cycle, to see the output.
If you don't flush your output, your output is not guaranteed to be visible outside your program. The fact that it is not printing in your terminal is just a consequence of the default behavior in linux to do line buffering when the output is a tty. If you run your program on linux with its output piped to another thing, like
./your_program | cat
Then the default buffer will be MUCH larger, most likely it will be at least 4096 bytes. So nothing will get displayed until the big buffer gets full. but really, the behaviour is OS specific unless you flush std::cout yourself.
To flush std::cout, use :
std::cout << std::flush;
also, using
std::cout << std::endl;
is a shortcut to
std::cout << '\n' << std::flush;