...
In this non-compliant code example, the exit1()
is and exit2()
functions are registered by atexit()
to perform required cleanup upon program termination. However, if condition
evaluates to true, exit()
is called a second time, resulting in undefined behavior.
Code Block | ||
---|---|---|
| ||
#include <stdio.h> #include <stdlib.h> void exit1(void) { /* ...cleanup code... */ return; } void exit2(void) { if (/* condition */) { /* ...more cleanup code... */ exit(0); } return; } int main(void) { atexit(exit1); atexit(exit2); /* ...program code... */ exit(0); } |
Because all functions registered by the atexit()
function are called in the reverse order of their registration, if exit2()
exits in any way other than by returning, exit1()
will not be executed. This may also be true for atexit()
handlers installed by support libraries.
Compliant Solution
A function that is registered as an exit handler by atexit()
must exit by returning, and not in any other manner.
Code Block | ||
---|---|---|
| ||
#include <stdio.h> #include <stdlib.h> void exit1(void) { /* ...cleanup code... */ return; } void exit2(void) { if (/* condition */) { /* ...more cleanup code... */ } return; } int main(void) { atexit(exit1); atexit(exit2); /* ...program code... */ exit(0); } |
...