Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The C99 exit() function is used for normal program termination. Nested calls to exit() result in undefined behavior. This can only occur when exit() is invoked from a function registered with atexit().

No atexit() handler should terminate in any way other than by returning. It is important and potentially safety-critical for all the atexit() handlers to be allowed to perform their cleanup actions. This is particularly true because the main program doesn't always know about handlers that may have been installed by support libraries.

Non-Compliant Code Example

So that it might perform cleanup upon program termination, In this non-compliant code example, the exit1() is registered by atexit(). If to perform required cleanup upon program termination. However, if condition evaluates to true, exit() will be is called a second time, resulting in undefined behavior.

Code Block
bgColor#FFcccc
#include <stdio.h>
#include <stdlib.h>

void exit1(void) {
  if (/* condition */) {
    /* ...cleanup code... */
    exit(0);
  }
}

int main(void) {
  atexit(exit1);
  /* ...program code... */
  exit(0);
}

Compliant Solution

_Exit() and abort() will both immediately halt program execution, and may be used within functions registered by atexit().

Wiki Markup
According to C99, \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\]:

...

A function that is registered as an exit handler by atexit() must exit by returning, and not in any other manner.

Code Block
bgColor#ccccFF
#include <stdio.h>
#include <stdlib.h>

void exit1(void) {
  if (/* condition */) {
    /* ...cleanup code... */
  }
  return;
}

int main(void) {
  atexit(exit1);
  /* ...program code... */
  exit(0);
}

...