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

void func() {
int x = 10; // stack memory
}

📌 Heap (Free Store)

  • Used for dynamic memory

  • Manual allocation & deallocation

  • Larger than stack

  • Slower than stack

int *p = new int(10); // heap memory

🔹 2. Dynamic Memory Allocation (new)

Allocate Single Variable

int *p = new int;
*p = 20;

Allocate with Initialization

int *p = new int(30);

Allocate Array

int *arr = new int[5];

🔹 3. Deallocation (delete)

Delete Single Variable

delete p;
p = nullptr;

Delete Array

delete[] arr;
arr = nullptr;

⚠️ Always match:

  • newdelete

  • new[]delete[]


🔹 4. Memory Leak

Occurs when allocated memory is not released.

void leak() {
int *p = new int(10);
// delete missing → memory leak
}

✔ Fix:

delete p;

🔹 5. Dangling Pointer

Pointer refers to freed memory.

int *p = new int(10);
delete p;
// p still holds old address → dangling

✔ Fix:

p = nullptr;

🔹 6. Double Deletion ❌

int *p = new int(10);
delete p;
delete p; // ❌ undefined behavior

✔ Fix:

delete p;
p = nullptr;

🔹 7. nullptr (Safe Pointer)

int *p = nullptr;

if (p != nullptr) {
// safe to use
}

✔ Avoids accidental dereferencing


🔹 8. RAII (Resource Acquisition Is Initialization)

Core C++ principle:
Resources are acquired in constructors and released in destructors.

class Resource {
int *data;
public:
Resource() { data = new int(10); }
~Resource() { delete data; }
};

✔ Automatic cleanup
✔ Exception safe


🔹 9. Smart Pointers (Modern C++)

Prefer smart pointers over raw pointers.

unique_ptr

#include <memory>

unique_ptr<int> p = make_unique<int>(10);

  • Single owner

  • Auto deletes memory


shared_ptr

shared_ptr<int> p1 = make_shared<int>(20);
shared_ptr<int> p2 = p1;
  • Multiple owners

  • Reference counting


weak_ptr

weak_ptr<int> wp = p1;
  • Avoids circular references


🔹 10. malloc / free (Not Recommended in C++)

int *p = (int*)malloc(sizeof(int));
*p = 10;
free(p);

❌ 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 nullptr

  • Using uninitialized pointers


✅ Best Practices

  • Prefer stack allocation when possible

  • Use smart pointers instead of raw pointers

  • Always set pointers to nullptr after delete

  • Follow RAII

  • Avoid malloc/free in C++


📌 Summary

  • Stack = automatic, Heap = manual

  • new / delete manage heap memory

  • Smart pointers simplify memory management

  • RAII is the safest design principle

  • Memory bugs are dangerous—write defensively

You may also like...