The C atexit() function registers a normal-termination callback. Callbacks are invoked by exit() and by a normal return from main. Multiple registrations are allowed up to an implementation-defined capacity.
This function is declared in <stdlib.h>. Its contract matters as much as its call: validate every required precondition, check any documented sentinel, and keep ownership or host effects clear in the surrounding code. Success is 0, meaning the callback will participate in normal termination. Failure is nonzero, so code must not assume that cleanup was registered. The examples below move from the direct call to an edge condition and a practical use.
Syntax
Start with this concrete atexit() call:
C
atexit(cleanup);
Call
What it does
atexit(cleanup);
Registers a normal-termination callback using the concrete values shown.
Include <stdlib.h>. Also include headers that declare any types, limits, locale tools, or I/O functions used around the call.
Library declaration
C
int atexit(void (*function)(void));
Parameters
Parameter
Description
function
Pointer to a no-argument, no-return function to run during normal termination.
Return Value
Return Value
Description
0
Registration succeeded.
Nonzero
The callback could not be registered.
C Examples
Example 1 — Register one callback
This complete program demonstrates a distinct part of the atexit() contract and checks the result or precondition that matters for the scenario.
Step 3. Continue only after zero confirms registration.
Step 4. The selected termination path runs the confirmed callback.
Frequently Asked Questions
atexit() registers a normal-termination callback. Callbacks are invoked by exit() and by a normal return from main. Multiple registrations are allowed up to an implementation-defined capacity.
Include <stdlib.h> before calling atexit().
Success is 0, meaning the callback will participate in normal termination. Failure is nonzero, so code must not assume that cleanup was registered.
Registered callbacks run in reverse registration order during normal termination. They do not run after abort() or _Exit().
The function is specified by the C standard library. Exact limits, locale behavior, environment behavior, allocation capacity, or host effects can still vary where relevant.