Versions Compared

Key

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

...

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
bgColor#FFcccc
#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
bgColor#ccccFF
#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);
}

...