If there is more than one function that is registered via the atexit function, then these functions will be executed in LIFO order. To understand this, let's modify the preceding atexistprog1.c program to register two functions via the atexit function. We will save the modified program as atexistprog2.c as follows (atexistprog2.c):
#include <stdio.h>
#include <stdlib.h>
char *str;
void freeup1()
{
free(str);
printf( "Allocated memory is freed \n");
}
void freeup2()
{
printf( "The size of dynamic memory can be increased and decreased \n");
}
int main()
{
int retvalue;
retvalue = atexit(freeup1);
if (retvalue != 0) {
printf("Registration of function freeup1() for atexit ()
function failed\n");
exit(1);
}
retvalue = atexit(freeup2);
if (retvalue != 0) {
printf("Registration of function freeup2() for atexit ()
function failed\n");
exit(1);
}
str = malloc( 20 * sizeof(char));
if( str== NULL )
{
printf("Some error occurred in allocating memory\n");
exit(1);
}
printf("Enter a string ");
scanf("%s", str);
printf("The string entered is %s\n", str);
}
On compiling and executing the program, we get the following output:
Figure 14.2
This output confirms that the last registered function, freeup2, is executed first, followed by the first registered function, freeup1.
Now, let's move on to the next recipe!