Follow these steps to create a recipe that registers a function that executes automatically when a program terminates normally:
- Register a function using the atexit function.
- Allocate some memory dynamically and allow that memory to be pointed to by a pointer.
- Ask the user to enter a string and assign the string to the dynamically allocated memory block.
- Display the entered string on the screen.
- When the program terminates, the function registered via the atexit function is invoked automatically.
- The registered function simply frees up the dynamically allocated memory so that it can be used by other applications.
The program for registering a function that automatically executes when a program terminates is as follows (atexistprog1.c):
#include <stdio.h>
#include <stdlib.h>
char *str;
void freeup()
{
free(str);
printf( "Allocated memory is freed \n");
}
int main()
{
int retvalue;
retvalue = atexit(freeup);
if (retvalue != 0) {
printf("Registration of function 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);
}
Now, let's go behind the scenes to understand the code better.