free() Perform in C Library With Examples


View Dialogue

Enhance Article

Save Article

Like Article

When reminiscence blocks are allotted by calloc(), malloc(), or realloc()  capabilities, the C library operate free() is used to deallocate or launch the reminiscence blocks to cut back their wastage. 

free() operate in C ought to solely be used both for the pointers pointing to the reminiscence allotted utilizing malloc() or for a NULL pointer. free() operate solely frees the reminiscence from the heap and it doesn’t name the destructor. To destroy the allotted reminiscence and name the destructor we will use the delete() operator in C.

 

Syntax to Use free() operate in C

void free(void *ptr)

Right here, ptr is the reminiscence block that must be freed or deallocated.

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

Program 1: 

C

#embrace <stdio.h>

#embrace <stdlib.h>

int predominant()

{

  

    

    

    int* ptr;

    int n = 5;

  

    

    printf("Enter variety of Parts: %dn", n);

  

    scanf("%d", &n);

  

    

    ptr = (int*)calloc(n, sizeof(int));

  

    

    

    if (ptr == NULL) {

        printf("Reminiscence not allotted n");

        exit(0);

    }

    

    printf("Efficiently allotted the reminiscence utilizing calloc(). n");

  

    

    free(ptr);

  

    printf("Calloc Reminiscence Efficiently freed.");

  

    return 0;

}

Output

Enter variety of Parts: 5
Efficiently allotted the reminiscence utilizing calloc(). 
Calloc Reminiscence Efficiently freed.

Program 2:

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int predominant()

{

  

    

    

    int* ptr;

    int n = 5;

  

    

    printf("Enter variety of Parts: %dn", n);

  

    scanf("%d", &n);

  

    

    ptr = (int*)malloc(n * sizeof(int));

  

    

    

    if (ptr == NULL) {

        printf("Reminiscence not allotted n");

        exit(0);

    }

    

    printf("Efficiently allotted the reminiscence utilizing malloc(). n");

  

    

    free(ptr);

  

    printf("Malloc Reminiscence Efficiently freed.");

  

    return 0;

}

Output

Enter variety of Parts: 5
Efficiently allotted the reminiscence utilizing malloc(). 
Malloc Reminiscence Efficiently freed.