The free() function in C is used to free or deallocate the dynamically allocated memory and helps in reducing memory wastage. The C free() function cannot be used to free the statically allocated memory (e.g., local variables) or memory allocated on the stack. It can only be used to deallocate the heap memory previously allocated using malloc(), calloc() and realloc() functions.
The free() function is defined inside <stdlib.h> header file.

C free() Function
Syntax of free() Function in C
void free(void *ptr);
Parameters
- ptr is the pointer to the memory block that needs to be freed or deallocated.
Return Value
- The free() function does not return any value.
Examples of free()
Example 1:
The following C program illustrates the use of the calloc() function to allocate memory dynamically and free() function to release that memory.
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr;
int n = 5;
printf ( "Enter number of Elements: %d\n" , n);
scanf ( "%d" , &n);
ptr = ( int *) calloc (n, sizeof ( int ));
if (ptr == NULL) {
printf ( "Memory not allocated \n" );
exit (0);
}
printf ( "Successfully allocated the memory using "
"calloc(). \n" );
free (ptr);
printf ( "Calloc Memory Successfully freed." );
return 0;
}
|
OutputEnter number of Elements: 5
Successfully allocated the memory using calloc().
Calloc Memory Successfully freed.
Example 2:
The following C program illustrates the use of the malloc() function to allocate memory dynamically and free() function to release that memory.
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr;
int n = 5;
printf ( "Enter number of Elements: %d\n" , n);
scanf ( "%d" , &n);
ptr = ( int *) malloc (n * sizeof ( int ));
if (ptr == NULL) {
printf ( "Memory not allocated \n" );
exit (0);
}
printf ( "Successfully allocated the memory using "
"malloc(). \n" );
free (ptr);
printf ( "Malloc Memory Successfully freed." );
return 0;
}
|
OutputEnter number of Elements: 5
Successfully allocated the memory using malloc().
Malloc Memory Successfully freed.