Dynamic Memory Allocation (DMA) in C++
Gaurav
Posted on September 6, 2024
DMA, or Dynamic Memory Allocation, is a fascinating and fundamental topic in computer science. Despite its importance, many students find it confusing or difficult to understand. In this article, I will thoroughly explain DMA and demonstrate how it can be used in the C++ programming language.
Contents
- What is DMA
- Memory Management in C++
- Static or Compile time memory allocation
- Dynamic or Runtime memory allocation
- Need of DMA
- DMA in C++
- Advantages of DMA
- Applications of DMA
- Conclusion
1. What is DMA
As the term suggests, Dynamic Memory Allocation refers to the process of reserving / allocating a portion of memory for a program upon request and releasing / deallocating it when it is no longer needed. All such memory allocation and deallocation occur at runtime. We'll explore how this mechanism functions and why it's essential in the upcoming topics.
2. Memory Management in C++
When discussing memory management in C++, there are two types - Static memory (Stack) and Dynamic memory (Heap).
a) Stack
The stack supports static memory allocation in C++. Memory in the stack is automatically allocated based on function calls; when a function is called, memory is allocated, and when the function execution completes, the memory is released or deallocated. The size of the stack is limited. In this context 'stack' refers to the same stack data structure that operates on the Last In First Out (LIFO) principle. This means that the most recently allocated memory is the first to be deallocated. However, it's important to note that the stack in C++ is also used for storing local variables and function call information, in addition to managing memory allocation.
b) Heap
The heap supports dynamic memory allocation in C++. This means that memory in the heap can be allocated and deallocated by the programmer as needed. Unlike the stack, which has a limited size, the heap generally offers more memory space. The total memory available in the heap is limited only by the physical memory available in the system.
3) Static or Compile time memory allocation
Here comes the stack memory in picture. When writing code in C++ and executing it, the operating system allocates a required portion of memory for the program in the stack. Each function call adds or pushes a stack frame into the stack, and after execution, that stack frame is removed or popped out from the stack. This illustrates how static memory is allocated at compile time, and as users or programmers, we don't have direct access to this stack memory.
4) Dynamic or Runtime memory allocation
Here comes the heap in picture. When writing C++ code to allocate memory, it gets allocated in the heap, and we receive the address of that allocated memory block. This memory remains available for the programmer's use until the program terminates or the user manually frees or releases the memory. To prevent memory wastage & to avoid memory leak, it's essential to free up the memory when it's no longer in use.
5) Need of DMA
In C++, Direct Memory Access (DMA) serves as a crucial tool for efficient memory handling. It allows users to manage memory effectively, allocating the required amount when needed and releasing it when no longer necessary. This capability enables developers to optimize resource utilization, avoiding unnecessary memory overhead. DMA also plays a pivotal role in preventing memory leaks and enhancing program stability by facilitating dynamic memory allocation and deallocation. In C++, where manual memory management is prevalent, DMA serves as a fundamental mechanism for developers to ensure efficient memory usage, leading to the creation of more robust and resource-efficient software solutions.
6) DMA in C++
To implement DMA in C++, a fundamental concept to grasp is Pointers. Pointers are variables that store memory addresses, allowing for direct access to memory locations. There are abundant resources available online for learning about pointers, some of which are listed at the end of this article.
In C++, there exist built-in operators for performing DMA, namely new and delete. These operators are similar to the memory allocation functions malloc, calloc, realloc, and free found in the C Programming Language. They enable dynamic memory allocation and deallocation, providing flexibility and efficiency in managing memory resources within C++ programs.
a) new
operator
new operator is used in C++ to dynamically allocate memory in heap. Whenever new
operator allocated memory it returns address of that allocated memory block which we can store in a pointer for further use. By storing the memory address in a pointer, developers gain direct access to the allocated memory, allowing for manipulation and retrieval of data as needed within the program.
#include <iostream>
using namespace std;
int main(){
int* pointer;
pointer = new int(12);
cout<<"Value is :- "<<*pointer;
return 0;
}
let's breakdown the code to understand it in detail,
-
int* pointer;
this is a pointer. -
pointer = new int(12);
here a memory block will be allocated to store integer value and it will be initialized with value 12. The address of this memory block will be stored in pointer. -
cout<<"Value is :- "<<*pointer;
this line will print the value using the dereference operator (*
).
In similar way we can allocate memory for arrays and objects of class.
// Dynamically allocating memory for array;
#include<iostream>
using namespace std;
int main(){
int* pointer;
pointer = new int[3] {11,12,13};
for(int i=0; i<3; i++){
cout<<*(pointer+i)<<endl;
}
return 0;
}
-
pointer = new int[3] {11,12,13};
this line will allocate the memory for array and will also initialize array with values where[3]
indicates the size of array. One can also use loop and other valid C++ methods to enter the values in array.
// Dynamically allocating memory for objects;
#include<iostream>
using namespace std;
class Myclass{
int value;
public:
// constructor will be called when creating object of class;
Myclass(){
this->value = 10;
}
void printvalue(){
cout<<"Value is :- "<<this->value;
}
};
int main(){
Myclass* obj = new Myclass;
// member function can be accessed with both of the below ways;
obj->printvalue();
// (*obj).printvalue();
return 0;
}
-
Myclass* obj = new Myclass;
this will create memory for object of Myclass. One thing to remember is that, whenever object of a class is created constructor is called, here also the default constructor of Myclass will be called as we are creating object of the class. -
obj->printvalue();
by this syntax we can access the member functions of class.(*obj).printvalue();
this syntax can also be used and the result will be same in both the cases.
b) delete
operator
As the name suggests delete
is used to de-allocate the allocated memory. It is necessary to free up the reserved memory block if not in use to avoid the memory wastage and to prevent memory leaks which can lead to performance issues and instability in programs. Below is an example code snippet demonstrating how delete is used..
#include <iostream>
using namespace std;
int main(){
int* pointer1 = new int(12); // for single int value;
int* pointer2 = new int[3] {11,12,13}; // for array;
cout<<*pointer1<<endl;
cout<<*pointer2<<endl;
// de-allocate / free up the memory;
delete pointer1;
delete[] pointer2;
return 0;
}
-
cout<<*pointer2<<endl;
will print the first array element. -
delete pointer1;
will deallocate memory of first integer value. -
delete[] pointer2;
will free up the memory of array.
7. Advantages of DMA
- Efficient Memory Management
- Improved Performance
- Avoid memory wastage
- More available size
- Allows memory sharing
8. Applications of DMA
One of the very common application of DMA is that it is used to code dynamic data structures like linked list, trees, graphs, etc.
9. Conclusion
In conclusion, Dynamic Memory Allocation (DMA) is a important concept in computer science which plays a crucial role in memory management. By using it, one can efficiently handle memory requirements. It offers flexibility, scalability and optimization. Feel free to share any suggestions or let me know if any changes are needed.
Resources
Posted on September 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.