How to Release Memory in C?

In C programming, releasing memory means deallocating memory that was previously allocated dynamically using functions like malloc(), calloc(), or realloc(). In this article, we will learn how to release memory in C.

Free Dynamic Memory in C

To release the dynamically allocated memory, we can use the free() function in C. The free function takes a pointer as an argument that points to the memory block allocated by the malloc(), calloc(), or realloc() functions and deallocates the memory making it available for reuse.

Syntax of free()

free(ptr);

here,

  • ptr is the pointer that points to the dynamically allocated memory block.

Note: Static memory (i.e. memory allocated on the stack) cannot be deleted by the user.

C Program to Release Allocated Memory

The following program illustrates how we can release memory in C using free() function:

C
// C Program to release dynamically allocated memory
#include <stdio.h>
#include <stdlib.h>

int main()
{

    /* ____ Release memory for an integer  ______ */

    // Allocate memory for a single integer
    int* ptr_single = (int*)malloc(sizeof(int));
    if (ptr_single == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Use the allocated memory for a single variable
    *ptr_single = 42;
    printf("Value of variable: %d\n", *ptr_single);

    // Release the memory allocated for the single variable
    free(ptr_single);
    printf("Memory for variable released\n");

    // Set the pointer to NULL to avoid dangling pointers
    ptr_single = NULL;

    /* ____ Release memory for a dynamically allocated array
     * ______ */

    // Allocate memory for an array of integers
    int* ptr_array = (int*)malloc(5 * sizeof(int));
    if (ptr_array == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Use the allocated memory for an array
    for (int i = 0; i < 5; i++) {
        ptr_array[i] = i;
    }
    printf("Array elements:");
    for (int i = 0; i < 5; i++) {
        printf("%d ", ptr_array[i]);
    }

    // Release the memory allocated for the array
    free(ptr_array);
    printf("\nMemory for array released\n");

    // Set the pointer to NULL to avoid dangling pointers
    ptr_array = NULL;

    return 0;
}

Output
Value of variable: 42
Memory for variable released
Array elements:0 1 2 3 4 
Memory for array released

Time Complexity: O(1), here denotes the number of elements in the array.
Auxiliary Space: O(1)