C++ Memory Management
🧠 C++ Memory Management
Memory management in C++ is about allocating, using, and releasing memory correctly to make programs fast, safe, and leak-free.
C++ gives you manual control, which is powerful—but requires care.
🔹 1. Memory Areas in C++
📌 Stack
Stores local variables
Automatic allocation/deallocation
Fast
Limited size
📌 Heap (Free Store)
Used for dynamic memory
Manual allocation & deallocation
Larger than stack
Slower than stack
🔹 2. Dynamic Memory Allocation (new)
Allocate Single Variable
Allocate with Initialization
Allocate Array
🔹 3. Deallocation (delete)
Delete Single Variable
Delete Array
⚠️ Always match:
new→deletenew[]→delete[]
🔹 4. Memory Leak
Occurs when allocated memory is not released.
✔ Fix:
🔹 5. Dangling Pointer
Pointer refers to freed memory.
✔ Fix:
🔹 6. Double Deletion ❌
✔ Fix:
🔹 7. nullptr (Safe Pointer)
✔ Avoids accidental dereferencing
🔹 8. RAII (Resource Acquisition Is Initialization)
Core C++ principle:
Resources are acquired in constructors and released in destructors.
✔ Automatic cleanup
✔ Exception safe
🔹 9. Smart Pointers (Modern C++)
Prefer smart pointers over raw pointers.
unique_ptr
Single owner
Auto deletes memory
shared_ptr
Multiple owners
Reference counting
weak_ptr
Avoids circular references
🔹 10. malloc / free (Not Recommended in C++)
❌ No constructors/destructors
✔ Use only for C compatibility
🔁 Stack vs Heap
| Stack | Heap |
|---|---|
| Automatic | Manual |
| Fast | Slower |
| Limited size | Large |
| Safe | Error-prone |
⚠️ Common Memory Errors
Memory leak
Dangling pointer
Double delete
Dereferencing
nullptrUsing uninitialized pointers
✅ Best Practices
Prefer stack allocation when possible
Use smart pointers instead of raw pointers
Always set pointers to
nullptrafterdeleteFollow RAII
Avoid
malloc/freein C++
📌 Summary
Stack = automatic, Heap = manual
new/deletemanage heap memorySmart pointers simplify memory management
RAII is the safest design principle
Memory bugs are dangerous—write defensively
