views:

78

answers:

2

In C, when the main process ends -- how does it know to call any functions registered with atexit()?

I understand how atexit() works, but I don't understand the communication between "Main process ending" and "call any functions registered with atexit()" I'm being a bit redundant.

Thanks!

+5  A: 

In C, the main() function is actually called by some other function, which is built into the runtime. This function, after the main() function ends, does a few more things to clean up. One of them is to call any functions which have been registered with the atexit(). This function actually stores some kind of static list of function pointers, which will be called by the runtime after main().

Avi
The file is often called crt0.o; it basically does the setup work, then executes `exit(main(argc, argv));`
Jonathan Leffler
+1  A: 

From the C standard [PDF Link] (5.1.2.2.3):

a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

It is the responsibility of the exit function to call the functions registered with atexit (see 7.20.4.3 in the standard for a description of everything that exit does).

James McNellis
Yes, I was stepping though the code of exit, and noticed it has an explicit call to atExit().Is there another way to do this by playing around with stack (without overrwriting the return address) so that it enters myExit() function when Main ends.Thanks!
Setzer
More likely the compiler emits code which: initializes globals; then calls main; then calls exit with the return value from main.
Steve Jessop