C library - free() function



The C stdlib library free() function is used to deallocate or release the memory that was previously allocated by the dynamic memory allocation functions such as calloc(), malloc(), or realloc().

This function helps to prevent memory leaks by allowing programmers to release memory that is no longer needed.

Syntax

Following is the C library syntax of the free() function −

void free(void *ptr)

Parameters

This function accepts a single parameter −

  • *ptr − It represents a pointer to the memory block that need to be freed or deallocate.

Return Value

This function does not returns any values.

Example 1

Let's create a basic c program to demonstrate the use of free() function.

#include <stdio.h>
#include <stdlib.h>

int main() {	
   //allocate the memory
   int *ptr = (int*)malloc(sizeof(int));
   if (ptr == NULL) {
      fprintf(stderr, "Memory allocation failed!\n");
      return 1;
   }
   
   *ptr = 42;
   printf("Value: %d\n", *ptr);
   
   // free the allocated memory
   free(ptr);
   
   // Set 'ptr' NULL to avoid the accidental use
   ptr = NULL;
   return 0;
}

Output

Following is the output −

Value: 42

Example 2

In this example, we allocate the memory dynamically, and after the allocation we free the memory using free() function.

#include <stdio.h>
#include <stdlib.h>

int main() {
   int *ptr;
   int n = 5;
   
   // Dynamically allocate memory using malloc()
   ptr = (int*)malloc(n * sizeof(int));
   
   // Check if the memory has been successfully allocated
   if (ptr == NULL) {
      printf("Memory not allocated.\n");
      exit(0);
   }
   else {
      // Memory has been successfully allocated
      printf("Memory successfully allocated.\n");
      
      // Free the memory
      free(ptr);
      printf("Memory successfully freed.\n");
   }
   return 0;
}

Output

Following is the output −

Memory successfully allocated.
Memory successfully freed.
Advertisements