How it works...

Using the atexit function, register a function called freeup, ensuring that the freeup function will be invoked if the program terminates normally. The value returned by the atexit function is checked to see that it is zero only. If the value returned by the atexit function is a nonzero value, then that means the function is not registered successfully and the program will terminate after displaying an error message.

If the function is registered successfully, 20 bytes are dynamically allocated and the allocated memory block is assigned to a character pointer, str. If the str pointer is NULL, then this means an error has occurred in the allocation of the memory block. If it is confirmed that the str pointer is not NULL and is pointing to a memory block, the user will be asked to enter a string. The string entered by the user is assigned to the memory block pointed to by the str pointer. The string entered by the user is then displayed on the screen, and, finally, the program terminates. However, before the program terminates, the function that is registered using the atexit function, freeup, is invoked. The freeup function frees the memory allocated to the str pointer and displays a message: Allocated memory is freed

The program is compiled using GCC, as shown in the following screenshot. Because no error appears during compilation, the atexistprog1.c program has successfully compiled into a .exe file: atexistprog1.exe. Upon executing this file, the user is prompted to enter a string that is assigned to the dynamically allocated memory. On program termination, the function registered with atexit is executed, which frees up the dynamically allocated memory, as is confirmed by the text message in the following screenshot:

Figure 14.1

Voilà! We have successfully registered a function that is called when the program exits.