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.
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.