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
newanddelete - 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 :
