C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Free memory using free() function

C Program: Free memory using free() function

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int *arr;

    int n, i;

 

    // Step 1: Allocate memory dynamically

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    arr = (int*) malloc(n * sizeof(int));  // allocate memory

    if (arr == NULL) {

        printf("Memory allocation failed!\n");

        return 1;

    }

 

    // Step 2: Input array elements

    printf("\nEnter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        printf("Element %d: ", i + 1);

        scanf("%d", &arr[i]);

    }

 

    // Step 3: Display the array

    printf("\nArray elements are:\n");

    for (i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

 

    // Step 4: Free the allocated memory

    free(arr);

    arr = NULL;  // good practice to set pointer to NULL after freeing

 

    printf("\n\nMemory successfully freed.\n");

 

    return 0;

}

Output

 
OUTPUT :
Enter number of elements: 5

Enter 5 elements:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50

Array elements are:
10 20 30 40 50 

Memory successfully freed.
 

Explanation

Step

Description

malloc()

Allocates memory dynamically at runtime.

free(pointer)

Deallocates (releases) the memory previously allocated by malloc(), calloc(), or realloc().

arr = NULL;

Prevents accessing freed memory (dangling pointer).