๐พ C++ Dynamic Memory Management โ Control Memory with new and delete
๐งฒ Introduction โ Why Dynamic Memory Management Matters in C++
C++ allows fine-grained control over how and when memory is allocated and released. Unlike automatic (stack) memory, dynamic memory is allocated at runtime on the heap using new
and deallocated using delete
. This is essential for building scalable, high-performance applications with variable-sized structures and long-living objects.
๐ฏ In this guide, youโll learn:
- What dynamic memory is and how it works
- How to use
new
,delete
,new[]
,delete[]
- Memory leaks, dangling pointers, and safe handling
- Best practices and real-world use cases
๐ What Is Dynamic Memory in C++?
Dynamic memory is memory allocated during runtime instead of compile-time. It’s used when:
- The size of data is unknown in advance
- Objects must live beyond the function scope
Allocated using new
, released using delete
.
๐ป Code Examples โ With Output
โ Example 1: Dynamic Allocation of a Single Integer
#include <iostream>
using namespace std;
int main() {
int* ptr = new int(42); // allocate memory and assign 42
cout << *ptr << endl;
delete ptr; // free memory
return 0;
}
๐ข Output:
42
โ Example 2: Dynamic Array Allocation
int* arr = new int[5]; // allocate array of 5 ints
for (int i = 0; i < 5; i++) arr[i] = i + 1;
delete[] arr; // use delete[] for arrays
๐ฆ new and delete Syntax
Operation | Syntax Example |
---|---|
Allocate single item | int* p = new int(10); |
Allocate array | int* a = new int[5]; |
Delete item | delete p; |
Delete array | delete[] a; |
๐ฅ Common Issues & How to Avoid Them
โ Memory Leak
Occurs when new
is used but delete
is never called.
โ
Use smart pointers (like unique_ptr
) or ensure delete
is always paired.
โ Dangling Pointer
Occurs when you access memory after deleting it.
โ
Set pointers to nullptr
after deleting them.
โ Double Delete
Calling delete
on the same pointer twice.
โ
Use nullptr
checks: if (ptr) delete ptr;
๐ Dynamic vs Automatic Memory
Feature | Automatic (stack) | Dynamic (heap) |
---|---|---|
Allocation Time | Compile-time | Runtime |
Scope | Limited to function/block | Custom scope |
Deallocation | Automatic | Manual (delete ) |
Flexibility | Fixed size | Variable size |
Lifetime | Temporary | Persistent until deleted |
๐ก Best Practices & Tips
๐ Best Practice: Always pair new
with delete
, and new[]
with delete[]
.
๐ก Tip: Prefer smart pointers like std::unique_ptr
or std::shared_ptr
for automatic cleanup.
โ ๏ธ Pitfall: Donโt use delete
on memory not allocated with new
.
๐ ๏ธ Use Cases for Dynamic Memory
๐งฎ Variable-Size Data: Allocate memory for arrays or matrices whose size is determined at runtime
๐ฆ Long-Lived Objects: Objects that must persist beyond function calls or scopes
๐ Data Structures: Linked lists, trees, graphs often require dynamic nodes
๐ง Object Pools: Reuse memory efficiently in real-time systems
๐ Summary โ Recap & Next Steps
๐ Key Takeaways:
- Dynamic memory in C++ gives runtime control via
new
anddelete
- Always manage memory safely to avoid leaks and crashes
- Smart pointers are a modern, safer alternative
โ๏ธ Real-World Relevance:
Used in game engines, data processing, large-scale applications, and memory-intensive systems like simulations and device drivers.
โ
Next Steps:
Learn about C++ Smart Pointers to manage dynamic memory safely and automatically.
โFAQ โ C++ Dynamic Memory Management
โWhat is the difference between delete
and delete[]
?delete
deallocates a single object, while delete[]
deallocates arrays created with new[]
.
โCan I use malloc
in C++?
Yes, but itโs not recommendedโuse new
/delete
or smart pointers for type safety and constructors.
โIs dynamic memory automatically freed when a program ends?
Yes, but this is not safe practice. Always delete
what you new
.
โHow can I prevent memory leaks?
Use smart pointers (unique_ptr
, shared_ptr
) or always match new
with delete
.
โWhat happens if new
fails?
It throws std::bad_alloc
unless new (nothrow)
is used.
Share Now :