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

后端 未结 3 868
悲哀的现实
悲哀的现实 2021-01-17 12:08

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

#include 

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

If in line 1

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-17 12:31

    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.

提交回复
热议问题