c / intermediate
Snippet
Automatic Cleanup with atexit
The atexit function registers a callback that is automatically executed when the program terminates normally via return from main or exit(). This ensures that essential cleanup logic runs without needing to manually call it at every exit point.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>#include <stdlib.h>void cleanup_handler(void) {printf("Cleaning up global resources...\n");}int main(void) {if (atexit(cleanup_handler) != 0) {fprintf(stderr, "Failed to register cleanup function.\n");return EXIT_FAILURE;}printf("Application logic running...\n");// When main returns, cleanup_handler is called automatically.return EXIT_SUCCESS;}
Breakdown
1
atexit(cleanup_handler)
Registers the function pointer to be called at program exit.
2
void cleanup_handler(void)
The registered function must take no arguments and return void.