Module 13: Dynamic Memory ManagementIntermediate55 min read
Stack vs Heap, new/delete, RAII & Smart Pointers (unique_ptr, shared_ptr, weak_ptr)
Master heap allocation with new/delete, prevent memory leaks and double deletion with RAII, and use C++11 smart pointers properly.
Key Takeaways & Core Concepts
- Stack: Automatic, fast LIFO allocation; bounded size.
- Heap: Dynamic runtime allocation; persists until explicitly freed. Always pair
newwithdeleteandnew[]withdelete[]. - Memory Leak: Forgetting
deleteor throwing an exception beforedelete. - Circular `shared_ptr`: Parent holds
shared_ptrto Child and Child holdsshared_ptrto Parent -> useweak_ptron the back-reference!
1. Stack vs. Heap & Raw `new` / `delete`
- Stack: Automatic, fast LIFO allocation; bounded size.
- Heap: Dynamic runtime allocation; persists until explicitly freed. Always pair
newwithdeleteandnew[]withdelete[].
1. unique_ptr Ownership Transfer & weak_ptr Observer
1#include <iostream>
2#include <memory>
3
4int main() {
5 auto u1 = std::make_unique<int>(99);
6 auto u2 = std::move(u1); // Ownership transferred
7 std::cout << "u1 is " << (u1 ? "non-null" : "null") << ", *u2 = " << *u2 << "\n";
8
9 auto sp = std::make_shared<int>(500);
10 std::weak_ptr<int> wp = sp;
11 if (auto locked = wp.lock()) {
12 std::cout << "weak_ptr locked: " << *locked << ", count=" << sp.use_count() << "\n";
13 }
14 return 0;
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: Demonstrates `std::move` on `unique_ptr` and safe `weak_ptr::lock()`.
2. RAII (Resource Acquisition Is Initialization)
RAII binds resource ownership (heap memory, file handles, sockets, mutexes) to stack object lifetime: acquire in constructor, release in destructor—making code exception-safe and leak-free.
3. Smart Pointers (`<memory>`, C++11/14)
| Smart Pointer | Ownership | Copyable? | Overhead | Creation |
|---|---|---|---|---|
| `std::unique_ptr` | Exclusive | No (Movable) | Zero | std::make_unique<T>() |
| `std::shared_ptr` | Shared (ref-counted) | Yes | Atomic ref count | std::make_shared<T>() |
| `std::weak_ptr` | Non-owning observer | Yes | Breaks cycles | From shared_ptr |
4. Common Mistakes
- Memory Leak: Forgetting
deleteor throwing an exception beforedelete. - Circular `shared_ptr`: Parent holds
shared_ptrto Child and Child holdsshared_ptrto Parent -> useweak_ptron the back-reference!
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)