C Program to Release Allocated Memory
The following program illustrates how we can release memory in C using free() function:
// 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)
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.