Dynamic memory allocation in C++ allows memory to be allocated during program execution. It helps programs use memory efficiently according to their needs.
What is Dynamic Memory Allocation?
Dynamic memory allocation means creating memory at runtime instead of compile time. The memory is allocated from heap memory using pointers.
Why Use Dynamic Memory Allocation?
Dynamic memory allocation is useful because it:
- Allocates memory when needed
- Saves unused memory
- Supports flexible program design
- Helps manage large data dynamically
Heap Memory
Dynamic memory is stored in the heap area of memory.
Unlike stack memory, heap memory is manually managed by the programmer.
Operators Used
C++ provides:
new→ allocate memorydelete→ free memory
Allocating Single Variable
int *ptr = new int;
Assigning Value
*ptr = 100;
Example Program
#include <iostream>
using namespace std;
int main() {
int *ptr = new int;
*ptr = 50;
cout << *ptr << endl;
delete ptr;
return 0;
}
Output
50
How Dynamic Allocation Works
newallocates memory in heap- Pointer stores memory address
- Data is accessed using pointer
deletefrees allocated memory
Dynamic Array Allocation
int *arr = new int[5];
This creates an array of 5 integers dynamically.
Example of Dynamic Array
#include <iostream>
using namespace std;
int main() {
int size = 5;
int *arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
for (int i = 0; i < size; i++) {
cout << arr[i] << endl;
}
delete[] arr;
return 0;
}
delete vs delete[]
| delete | delete[] |
|---|---|
| Used for single variable | Used for arrays |
| Frees one memory block | Frees multiple memory blocks |
Null Pointer After Deletion
Good practice:
ptr = nullptr;
This avoids dangling pointers.
Memory Leak
A memory leak happens when allocated memory is not released.
Example of Memory Leak
int *ptr = new int;
// forgot delete
Dangling Pointer
A dangling pointer points to memory that has already been freed.
delete ptr;
After deletion:
ptr = nullptr;
Advantages of Dynamic Memory Allocation
- Flexible memory usage
- Efficient resource management
- Useful for large programs
- Supports dynamic data structures
Disadvantages
- Manual memory handling required
- Risk of memory leaks
- More complex than static memory
Why Dynamic Memory Allocation is Important
It is important because it:
- Allows efficient memory management
- Supports linked lists, trees, and graphs
- Helps build scalable applications
- Is essential for advanced programming
Real-Life Example
Think of renting rooms in a hotel:
- Rooms are booked only when needed
- Unused rooms are released later
Dynamic memory works similarly by allocating memory only when required.
Conclusion
Dynamic memory allocation in C++ allows programmers to manage memory during runtime using new and delete. It provides flexibility, efficient memory usage, and support for advanced programming concepts and data structures.