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
C Programming Language Tutorial C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() In C, a variable defined in a function is stored in the stack memory. The requirement of this memory is that it needs to know the size of the data to memory at compile time (before the program runs). Also, once defined, we can neither change the size nor completely delete the memory.To resolve this,
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read