free() Function in C Library With Examples

View Discussion

Improve Article

Save Article

When memory blocks are allotted by calloc(), malloc(), or realloc()  functions, the C library function free() is used to deallocate or release the memory blocks to reduce their wastage. 

free() function in C should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. free() function only frees the memory from the heap and it does not call the destructor. To destroy the allocated memory and call the destructor we can use the delete() operator in C.

 

Syntax to Use free() function in C

void free(void *ptr)

Here, ptr is the memory block that needs to be freed or deallocated.

For example, program 1 demonstrates how to use free() with calloc() in C and program 2 demonstrates how to use free() with malloc() in C.

Program 1: 

C

#include <stdio.h>

#include <stdlib.h>

int main()

{

  

    

    

    int* ptr;

    int n = 5;

  

    

    printf("Enter number of Elements: %dn", 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;

}

Output

Enter number of Elements: 5
Successfully allocated the memory using calloc(). Calloc Memory Successfully freed.

Program 2:

C

#include <stdio.h>

#include <stdlib.h>

  

int main()

{

  

    

    

    int* ptr;

    int n = 5;

  

    

    printf("Enter number of Elements: %dn", 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;

}

Output

Enter number of Elements: 5
Successfully allocated the memory using malloc(). Malloc Memory Successfully freed.