What does main() return on run-time exception?

2019-07-04 01:23发布

问题:

What does the C int main() function return when the program hits a run-time exception (e.g. segmentation fault)?

When searching for an answer I hit many discussions/posts about what main() should return, like this one.

回答1:

It (the main function) doesn't return if the program crashes. If a program crashes, then the operating system would have killed the program, so the program isn't running anymore and that includes the main function. A program that doesn't run can't return anything on its own. What is "returned" to the running environment depends on the operating system, which have taken over after the program.

Whatever is returned is handled by the operating system. For POSIX systems, a process that is killed by a signal (like SIGSEGV, segmentation fault) the OS will return 128 plus the signal number. This is documented in e.g. this waitpid reference page (and the links from it).

For Windows it's typically reported as a cryptic long value (usually the value 0x80000000 plus other flags and data).

For older or more primitive operating systems that don't handle crashes, the value being "returned" is usually what happen to be in the "return value" register or on top of the stack at the time of the crash.



回答2:

If a program crashes, it will not return any value. It will be up to the operating system to handle that, but the C standard does not say anything about what should happen. When calling a program, the behavior can be described like this:

int mainWrapper() {
    int ret;
    try {
        ret = main();
    }
    catch(Exception e) {
        ret = // Some value that may or may not depend on what 
              // happened and might even be random
    }
    return ret;
}

What happens in reality when you call a function in machine code is that you simply store the address of where in the code you are at a certain place and then do a jump to the code you want to execute. That code may have some assumptions about some registers containing the arguments you want to pass to that function. If you forgot to load those registers, the code will use whatever was there without knowing that you forgot to send the arguments. Same thing goes when the function ends. This happens when the machine code hits a certain return instruction. This instruction will jump back to where we called it. If the code after that expects the function to return something, it will basically just hope that the function stored its return value at the right place and then read it without knowing if this is the case.

So the short answer is that it might contain a random value or something that is decided by the operating system.



标签: c exception main