Using the free() Function in C


The free function in C is used to deallocate memory that was previously allocated by malloc, calloc, or realloc. It takes as an argument a pointer to the memory that needs to be freed. Once the memory has been freed, the pointer should not be used again as it may cause undefined behavior
      Syntax :
             free ( ) ;
      Example :
             free ( ptr ) ;

  • This program demonstrates the use of the malloc, free functions in C. The malloc function is used to dynamically allocate memory at runtime. In the above program, the getting_values() function is used to get the values of 3 integers from the user and stores them in a dynamically allocated memory using the malloc function.
  • The function getting_values() return the pointer ptr which points to the first byte of the dynamically allocated memory. main() function calls getting_values() and gets the pointer and uses it to calculate the sum of 3 integers.
  • After the calculation the free() function is called to free the memory allocated dynamically by malloc() function, so that the memory can be used again by the system. The pointer is set to NULL after freeing the memory.

Source Code

//free function
#include<stdio.h>
#include<stdlib.h>
 
int * getting_values()
{
    int i;
    int *ptr=(int *)malloc(3*sizeof(int));
    for(i=0; i<3; i++)
    {
        printf("Enter a integer : ");  //10,20,30
        scanf("%d",ptr+i);
    }
    return ptr;
}
 
int main()
{
    int i,n=0;
    int *ptr=getting_values();
     for(i=0; i<3; i++)
    {
        n+=*(ptr+i);  //n=n+10  => +20 =>+30
    }
     printf("Total : %d  ",n);
     free(ptr);
     ptr=NULL;
    return 0;
}
 
 
To download raw file Click Here

Output

Enter a integer : 11
Enter a integer : 12
Enter a integer : 13
Total : 36

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C