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
Similar Reads
delete keyword in C++ delete is an operator that is used to destroy array and non-array(pointer) objects which are dynamically created by the new operator.delete can be used by either using the delete operator or delete [ ] operator.The new operator is used for dynamic memory allocation which stores variables on heap mem
4 min read
Clean Up Memory in R In this R article, we will discuss how to clean up memory with its working example in the  R programming language. Let's first discuss removing objects from our workspace first. rm() function in R Language is used to delete objects from the workspace. It can be used with ls() function to delete all
2 min read
Memory leak in C++ In C++, memory leak is a situation where the memory allocated for a particular task remains allocated even after it is no longer needed. This leads to the wastage of memory because it is unavailable for other tasks till the end of the program.Why memory leak occurs in C++?In C++, there is no automat
3 min read
Self Destructing Code in C Using remove() function in C, we can write a program which can destroy itself after it is compiled and executed. Explanation: This can be done using the remove function in C. Note that, this is done in Linux environment. So, the remove function is fed the first parameter in command line argument i.e
1 min read
"delete this" in C++ Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefi
1 min read
Dereference Pointer in C We know that the pointer variable can store the memory address in C language and in this article, we will learn how to use that pointer to access the data stored in the memory location pointed by the pointer. What is a Pointer? First of all, we revise what is a pointer. A pointer is a variable that
4 min read