In C programming, we might allocate memory dynamically for various tasks but what happens when those pieces of memory are no longer needed? If not managed properly, they can lead to memory leaks, wasting valuable resources, and slowing down our program. Therefore, we need to manage memory in C by properly deallocating it when it's no longer in use to ensure that our programs run efficiently without unnecessary memory consumption.
In this article, we will discuss everything in detail about deleting memory in C, why it's important to free up memory, the common pitfalls we should avoid, and how to deallocate memory correctly with the help of examples.
Types of Memory Allocation in C
Before learning about memory deletion, it’s important to understand the basic difference between static and dynamic memory:
- Static Memory Allocation: It is allocated at compile-time and managed by the system. The system automatically handles the allocation and deallocation of this memory to make sure that it is reclaimed when no longer needed. For example, memory allocated to local variables is automatically reclaimed when a function ends, and for global variables memory is deallocated at program termination automatically.
- Dynamic Memory Allocation: It is allocated at runtime using functions like malloc(), calloc(), and realloc() and should be managed by us manually, how? That we will discuss here.
Memory Deallocation in C
Dynamic memory allocation in C allows us to allocate memory at runtime by using the functions like malloc(), calloc(), or realloc() that provide flexibility in memory management. However, it also requires manual deallocation that can be done using the free() function or realloc function when it's no longer in use to ensure that our programs run efficiently that is used to free or deallocate the dynamically allocated memory and helps in reducing memory wastage and avoiding memory leaks.
Syntax to Use free() Function in C
void free(void *ptr);
Here, ptr is the pointer to the memory block that we want to free or deallocate.
Free() Function in CExamples of Dynamic Memory Deallocation in C
The following examples illustrates how we can delete the memory allocated dynamically using the free() function.
Example 1: Deleting Dynamically Allocated Memory Using free()
The below C program illustrate how we can use the malloc() function to allocate memory dynamically and free() function to release that memory.
C
// C program to demonstrate use of
// free() function using malloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Dynamic memory allocated by using malloc
int* ptr = (int*)malloc(sizeof(int));
// Freeing the memory
free(ptr);
printf("ptr freed successfully\n");
return 0;
}
Outputptr freed successfully
Example 2: Deleting Dynamically Allocated Memory Using realloc()
The below C program illustrates how we can use the calloc() function to allocate memory dynamically and realloc() function to deallocate that memory.
C
// C program to demonstrate use of
// realloc() function to deallocate memory
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Allocate memory
int* ptr = (int*)calloc(10, sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Use the allocated memory
for (int i = 0; i < 10; i++) {
ptr[i] = i * 2;
}
// Deallocate memory using realloc to shrink size to
// zero
ptr = (int*)realloc(ptr, 0);
if (ptr == NULL) {
printf("Memory deallocated successfully using "
"realloc\n");
}
return 0;
}
OutputMemory deallocated successfully using realloc
Example 3: Deleting Dynamically Allocated Memory for a 2 Array
The below C program illustrates how we can use the free() function to deallocate the memory of a dynamically allocated 2D array.
C
// C program to demonstrate use of
// free() function to deallocate the memory of a dynamically
// allocated 2D array
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Define the number of rows and columns
int rows = 5;
int cols = 5;
// Allocate memory for a 2D array
int** array = (int**)malloc(rows * sizeof(int*));
if (array == NULL) {
// Check if memory allocation failed
printf("Memory allocation failed\n");
return 1;
}
// Allocate memory for each row
for (int i = 0; i < rows; i++) {
array[i] = (int*)malloc(cols * sizeof(int));
if (array[i] == NULL) {
// Check if memory allocation failed
printf("Memory allocation failed\n");
// Free previously allocated memory
for (int j = 0; j < i; j++) {
free(array[j]);
}
free(array);
return 1;
}
}
// Use the allocated memory to store values
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = i * j;
}
}
// Deallocate memory for each row
for (int i = 0; i < rows; i++) {
free(array[i]);
}
// Deallocate memory for the array of pointers
free(array);
// Print message indicating successful deallocation
printf("2D array freed successfully\n");
return 0;
}
Output2D array freed successfully
Points to Remember
The following are the important points and common mistakes that we must keep in mind while deallocating the dynamic memory in C.
1. Double Freeing
Freeing a pointer twice can lead to undefined behavior. Ensure that a pointer is not freed more than once.
int *ptr = (int *)malloc(10 * sizeof(int));
free(ptr);
free(ptr); // Undefined behavior
2. Freeing NULL Pointer
It is safe to call free() with a NULL pointer. It has no effect.
int *ptr = NULL;
free(ptr); // Safe, no effect
3. Dangling Pointers
After freeing a pointer, it's a good practice to set it to NULL to avoid dangling pointers, which point to freed memory.
int *ptr = (int *)malloc(10 * sizeof(int));
free(ptr);
ptr = NULL; // Good practice
4. Freeing Pointers to Local Variables
Do not ever use the free() function on pointers to stack-allocated (local) variables. This will lead to undefined behavior.
int x;
int *ptr = &x;
free(ptr); // Undefined behavior
5. Exceptions
- Attempting to free a non-pointer object results in an error.
- Attempting to free a pointer to a stack-allocated variable leads to undefined behavior.
Related Articles
Explore
C Basics
Arrays & Strings
Pointers and Structures
Memory Management
File & Error Handling
Advanced Concepts