Join Regular Classroom : Visit ClassroomTech

C standard library function – free()

In case of static memory allocation there are some drawbacks like: wastage of memory, less flexibility, permanent allocation of variables etc. To overcome these situations the concept of Dynamic Memory Allocation has been introduced. In dynamic memory allocation the memories can be allocated dynamically at run time.

There 4 library functions that are described under <stdlib.h> (Standard Library Functions)

1. malloc()
2. calloc()
3. realloc()
4. free()

In this article we’ll elaborately learn about free().

What is free()?

In dynamic memory allocation the memory have to be deallocated explicitly. It releases all the used memory spaces previously allocated by calloc(), malloc() or realloc() functions. If we no longer need the data stored in a particular block of memory, then we should have a practice to release that memory for future use. After freeing the memory blocks the memories are returned to heap.

free() is used to save unused memory by freeing it. Dynamic allocation have this advantage which static allocation lacks.

Syntax

free(ptr);

Lets take an example to understand.

/* C code to execute free() in DMA */
/* www.codewindow.in */

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

// Driver code
int main() {
    int *p, n;     // Pointer and the variables are initialized
    printf("Enter the size of array: ");
    scanf("%d", &n);

    p = (int*) calloc(n, sizeof(int));  // An int array of n elements has been assigned to the pointer
    
    if(p==NULL) {
        printf("\nMemory allocation unsuccessful using calloc");
        exit(0);
    }
    else {
        printf("\nMemory allocation successful using calloc");
        
        printf("\nEnter the elements of the array: ");
        for(int i=0; i<n; ++i)
            scanf("%d", p+i);   // Array elements are taken as input
        
        printf("\nThe elements of the array: ");
        for(int i=0; i<n; ++i)
             printf("%d ", *(p + i));   // Print element of the array
      
        free(p);     //frees the space allocated in the memory
        
        printf("\nMemory has been freed successfully using free");
    }
    
    return 0;
}

Input

Enter the size of array: 5
Enter the elements of the array: 1 2 3 4 5 

Output

Memory allocation successful using calloc
The elements of the array: 1 2 3 4 5 
Memory has been freed successfully using free

Explanation

Previously allocated memory was 5 * 4[no. of elements * sizeof(int)] = 20 bytes using calloc. By using the function “free()”, the space allocated to the memory has been deleted thereafter.


Follow Us


You Missed

Also Checkout