Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a guarantee of stdout auto-flush before exit? How does it work?

Here is the code (valid C and C++)

#include <stdio.h>

int main() {
    printf("asfd");
    // LINE 1
    return 0;
}

If in line 1 I put segfaulting expression the program would just crash without printing anything (as expected).

But why is the above code printing "asdf" and not exiting without buffer being flushed? What is under the hood and why does it work as expected?

like image 783
sasha.sochka Avatar asked Apr 09 '13 20:04

sasha.sochka


People also ask

What does it mean to flush stdout?

stdout. flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

Does exit flush buffers?

Will buffer be automatically flushed to disk when a process exits? In general the answer is no.

Does cout flush automatically?

A stream is flushed implicitly in the following situations: The predefined streams cout and clog are flushed when input is requested from the predefined input stream (cin). The predefined stream cerr is flushed after each output operation.

Does Endl automatically flush?

std::endl writes a newline to the output stream and flushes it. In most cases, the developer doesn't need to flush. Flushing operation is expensive, because it involves a system call. Instead of std::endl, you can simply write “\n”.


2 Answers

This is accomplished by these two sections in the C++ language specification:

[basic.start.main]

A return statement in main has the effect of leaving the main function and calling exit with the return value as the argument.

and

[lib.support.start.term]

The function exit has additional behavior in this International Standard:

  • ...
  • Next, all open C streams with unwritten buffered data are flushed.
  • ...
like image 50
Raymond Chen Avatar answered Oct 28 '22 11:10

Raymond Chen


Generally, a return from main is not the end of your program, nor is entry to main the start.

Usually, the linker that creates the final executable for your program marks some location, perhaps named start, as the place where execution is to begin. When the operating system loads your program and starts executing it, it starts execution at this place. There is code there that sets up an environment: Creates a stack, sets stream states, et cetera. Then this code calls main.

When main returns, it returns to this special code. That code then performs various clean-up work that is required at the end of a C or C++ program, as described in this answer.

If a program is terminated abruptly, this final code might not be executed.

like image 38
Eric Postpischil Avatar answered Oct 28 '22 11:10

Eric Postpischil