Course contentsShow
← C
Lesson 875 of 1,21912. The Standard LibraryFree lesson

Cleaning up at exit with `atexit`

Cleaning up at exit with atexit

What you'll learn: How to register "cleanup" functions that run automatically when your program finishes.

When a program ends, it's like a guest leaving a hotel room. Usually, the operating system is a good housekeeper—it reclaimed the memory and closes the files. However, sometimes you want your program to tidy up specific things before it disappears, like deleting a temporary file, logging a "Goodbye" message, or saving a final state to a database.

Instead of trying to catch every possible return statement or exit point in your code, C provides a convenient "automatic reminder" system called atexit.

Your Program’s To-Do List

The atexit() function, found in <stdlib.h>, allows you to register a specific function to be called automatically when your program terminates normally. Think of it like leaving a sticky note on the door: "Before you leave, please turn off the lights."

Here are the ground rules for using atexit:

  1. The function you register must take no arguments and return nothing (void).
  2. You can register multiple functions; they will run in the reverse order they were registered (the last one added is the first one executed).
  3. These functions only run if the program exits normally (via return from main or calling exit()). They won't run if the program crashes.

Practical Example

In this example, we register a cleanup function early on. No matter where the program ends, the cleanup will trigger.

#include <stdio.h>
#include <stdlib.h>

void cleanup(void) {
    printf("Cleaning up resources and closing logs...\n");
}

void say_goodbye(void) {
    printf("Goodbye, user!\n");
}

int main() {
    // Register the functions with the exit handler
    atexit(say_goodbye);
    atexit(cleanup);

    printf("Program is running. Preparing to exit...\n");

    // We don't need to call cleanup() manually.
    // Because we used atexit, it happens automatically.
    return 0;
}

When you run this, the output will show "Cleaning up resources..." followed by "Goodbye, user!" because of the reverse-order rule.

Why use it?

In complex programs, you might have dozens of places where an error could cause the program to stop. Instead of manually writing your cleanup code before every single exit(1) or return statement, you can register your cleanup function once at the start of main. This ensures your program always "leaves the room" the way it found it.

Key takeaway

Use atexit() to register functions that should automatically run at the end of your program's lifecycle to ensure a clean shutdown.