C++ Dynamic Memory Allocation: Heap Management, new/delete & Leak Prevention

Stack memory is fast but fixed in size. When your program needs to allocate memory whose size is only known at runtime (e.g., loading a 4K game texture or a 10,000-row database query), you must allocate memory dynamically on the Heap.

C++ Memory Architecture Stack vs Heap Segments
Figure 6: Program Memory Architecture: Stack (Automatic) vs Heap (Dynamic)

The new and delete Operators

#include <iostream>

int main() {
    // 1. Allocate a single integer on the Heap
    int* ptr = new int(250);
    std::cout << "Heap value: " << *ptr << "\n";

    delete ptr;         // Deallocate heap memory
    ptr = nullptr;      // Prevent dangling pointer!

    // 2. Allocate a dynamic array of integers on the Heap
    int size = 5;
    int* dynamicArr = new int[size]{10, 20, 30, 40, 50};

    // CRITICAL: Always use delete[] for arrays!
    delete[] dynamicArr;
    dynamicArr = nullptr;

    return 0;
}
What is a Memory Leak?

A memory leak occurs when heap memory is allocated with new, but the pointer holding its address is lost or reassigned without calling delete. The memory remains occupied until the operating system shuts down the process. In servers running 24/7, memory leaks cause the system to crash with std::bad_alloc.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between new/delete in C++ and malloc/free in C?

malloc() only allocates raw bytes and does NOT call constructors. 'new' allocates memory AND calls the object's constructor. Similarly, free() only deallocates bytes, while 'delete' calls the object's destructor before releasing the memory.

Q2. What catastrophic bug happens if you free an array with 'delete' instead of 'delete[]'?

Calling 'delete ptr' on an array allocated with 'new T[N]' only invokes the destructor for the FIRST element (index 0). The remaining N-1 objects never have their destructors called, causing massive resource leaks and Undefined Behavior.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Smart Pointers

Modern automated heap management (unique_ptr).

C++ RAII Idiom

Binding dynamic resources to deterministic scope destructors.

Exception Handling

Handling std::bad_alloc during out-of-memory errors.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!