Chapter 21 of 48

Dynamic Memory Allocation

Until now, every variable we created had a size that was fixed when we wrote the program. An array like int marks[50]; always holds exactly 50 integers, even if the class has only 12 students, or 80.

Real programs rarely know their sizes in advance. A text editor doesn't know how long your file will be. A game doesn't know how many enemies will appear. For situations like these, C++ lets us ask for memory while the program is running. This is called dynamic memory allocation.

In this topic, we'll learn how to allocate and free memory with new and delete, how this differs from malloc()/free() in C, and, most importantly, the classic bugs (memory leaks, dangling pointers, double delete) that every C++ programmer must learn to avoid. We will use what we learned in the Pointers and References topics throughout.


Stack vs Heap

When a C++ program runs, its variables live in different regions of memory. The two that matter here are the stack and the heap (the C++ standard calls the heap the free store).

┌──────────────────────────┐  high addresses
│          Stack           │  local variables, function parameters
│            ↓             │  (grows and shrinks automatically)
│                          │
│            ↑             │
│      Heap (free store)   │  memory we request with new
├──────────────────────────┤
│   Global / static data   │
├──────────────────────────┤
│      Program code        │
└──────────────────────────┘  low addresses

(This is the typical layout on desktop systems. The standard itself does not require any particular layout.)

FeatureStackHeap (free store)
Who manages it?The compiler, automaticallyThe programmer (new / delete)
When is memory released?When the variable goes out of scopeOnly when we call delete
Size decidedAt compile timeAt run time
Typical size limitSmall (often 1 MB on Windows, 8 MB on Linux)Large (limited by available memory)
SpeedVery fast (just moves a stack pointer)Slower (the allocator must find a free block)
LifetimeTied to the enclosing blockUntil delete, even after the function returns

So dynamic memory gives us two things the stack cannot:

  • A size chosen at run time (for example, read from the user).

  • A lifetime we control: the memory survives after the function that created it returns.

Note: int arr[n]; where n is a variable (a variable-length array) is not standard C++. GCC accepts it as an extension, but MSVC rejects it, and -Wpedantic warns about it. In standard C++, a run-time sized array must come from the heap.


The new Operator

The new operator allocates memory for an object on the heap, creates (constructs) the object in that memory, and returns a pointer to it.

Syntax:

Type* ptr = new Type;            // default-initialized
Type* ptr = new Type(value);     // initialized with value
Type* ptr = new Type{value};     // brace-initialized (C++11)
Type* ptr = new Type{};          // value-initialized (0 for numbers)

The object created by new has no name. The only way to reach it is through the pointer that new returns. If we lose that pointer, we lose the object.

The delete Operator

The delete operator destroys an object created by new and gives its memory back to the free store.

delete ptr;

delete does not change ptr itself. After delete, ptr still holds the old address, but that address no longer belongs to us. That's why it's a good habit to set the pointer to nullptr afterwards.

Example: Allocating Single Values

#include <iostream>

int main()
{
    int* p = new int;      // default-initialized: value is indeterminate
    *p = 42;               // so we assign before reading

    int* q = new int(7);   // direct-initialized with 7
    int* r = new int{};    // value-initialized: guaranteed 0
    double* d = new double{3.5};

    std::cout << "*p = " << *p << '\n';
    std::cout << "*q = " << *q << '\n';
    std::cout << "*r = " << *r << '\n';
    std::cout << "*d = " << *d << '\n';

    delete p;
    delete q;
    delete r;
    delete d;

    p = nullptr;           // good habit: no dangling pointer left behind
    delete p;              // deleting nullptr is safe and does nothing
    std::cout << "All memory released\n";
    return 0;
}

Output:

*p = 42
*q = 7
*r = 0
*d = 3.5
All memory released

Notice the difference between new int and new int{}:

ExpressionInitial value
new intIndeterminate (garbage). Reading it before assigning is undefined behavior.
new int() or new int{}0 (value-initialization)
new int(7) or new int{7}7

Here is what happens in memory for int* q = new int(7); (addresses are example values):

        Stack                         Heap
   ┌────────────┐              ┌────────────┐
 q │   0x5000   │ ───────────► │     7      │  (unnamed int)
   └────────────┘              └────────────┘
                                address 0x5000

The pointer q is an ordinary local variable on the stack. When main() ends, q disappears automatically, but the int on the heap does not. Only delete q; frees it.


Dynamic Arrays: new[] and delete[]

To allocate an array on the heap, we put the size in square brackets. The size can be any expression, including a variable whose value is known only at run time.

int* arr = new int[n];   // n ints on the heap
delete[] arr;            // must use delete[] for arrays

The pointer returned by new int[n] points to the first element, so we use it exactly like an array name: arr[i] or *(arr + i), as we saw in the Pointers topic.

Example: Marks of n Students

#include <iostream>

int main()
{
    int n;
    std::cout << "How many marks? ";
    std::cin >> n;

    int* marks = new int[n];          // size decided at run time

    for (int i = 0; i < n; i++)
    {
        std::cout << "Mark " << i + 1 << ": ";
        std::cin >> marks[i];
    }

    int total = 0;
    for (int i = 0; i < n; i++)
        total += marks[i];

    std::cout << "Total = " << total << '\n';
    std::cout << "Average = " << static_cast<double>(total) / n << '\n';

    delete[] marks;                   // array form, because we used new[]
    marks = nullptr;
    return 0;
}

Sample run (the user types 4, then 78, 85, 92 and 66):

How many marks? 4
Mark 1: 78
Mark 2: 85
Mark 3: 92
Mark 4: 66
Total = 321
Average = 80.25

The program uses exactly as much memory as it needs: 4 integers here, 400 if the user types 400.

Initializing Dynamic Arrays

#include <iostream>

int main()
{
    int* a = new int[5];          // values are indeterminate
    int* b = new int[5]();        // all five are 0
    int* c = new int[5]{10, 20};  // 10 20 0 0 0

    for (int i = 0; i < 5; i++) a[i] = i * i;   // fill a before reading it

    for (int i = 0; i < 5; i++) std::cout << a[i] << ' ';
    std::cout << '\n';
    for (int i = 0; i < 5; i++) std::cout << b[i] << ' ';
    std::cout << '\n';
    for (int i = 0; i < 5; i++) std::cout << c[i] << ' ';
    std::cout << '\n';

    delete[] a;
    delete[] b;
    delete[] c;
    return 0;
}

Output:

0 1 4 9 16 
0 0 0 0 0 
10 20 0 0 0 

With a brace list (C++11), the elements we don't list are value-initialized, so they become 0. If the list has more elements than the array size, the program does not compile when the size is a constant; when the size is a run-time value, new throws std::bad_array_new_length.

A few more rules worth knowing:

  • new int[0] is legal. It returns a valid, non-null pointer that we must not dereference, but we still must delete[] it.

  • If the size is negative at run time, new throws std::bad_array_new_length (since C++11).

  • There is no way to ask a pointer "how many elements do you point to?". We must remember the size ourselves.


Matching new with the Right delete

This is a rule you must never break:

Allocated withRelease with
new Tdelete p
new T[n]delete[] p
std::malloc()std::free(p)

Mixing them (for example new[] with delete, or new with free()) is undefined behavior. It may appear to work with int, but with class types the wrong number of destructors runs, and the program can corrupt memory or crash.

#include <iostream>

int main()
{
    int* arr = new int[4]{1, 2, 3, 4};
    std::cout << arr[0] << '\n';
    delete arr;          // WRONG: should be delete[] arr
    return 0;
}

GCC 15 already warns at compile time (-Wall is enough; the warning is not guaranteed in every situation, so never rely on it):

mismatch.cpp:7:12: warning: ‘void operator delete(void*, std::size_t)’ called on pointer returned from a mismatched allocation function [-Wmismatched-new-delete]
    7 |     delete arr;          // WRONG: should be delete[] arr
      |            ^~~
mismatch.cpp:5:37: note: returned from ‘void* operator new [](std::size_t)’

And if we build with AddressSanitizer (-fsanitize=address), the program stops at run time with (trimmed):

ERROR: AddressSanitizer: alloc-dealloc-mismatch (operator new [] vs operator delete)

What If Allocation Fails?

Memory is not infinite. When new cannot get the memory it needs, it does not return nullptr (unlike malloc()). Instead, it throws an exception of type std::bad_alloc.

If we really want a null pointer instead, we can use the nothrow form: new (std::nothrow) T. Both are declared in <new>.

We will study try/catch properly in the Exception Handling topic. For now, just read it as "try this, and if a bad_alloc happens, run the catch block".

#include <iostream>
#include <new>       // std::bad_alloc, std::nothrow
#include <cstddef>

int main()
{
    std::size_t huge = static_cast<std::size_t>(1) << 60;   // about 1 exabyte of ints

    // 1. Normal new throws std::bad_alloc on failure
    try
    {
        int* p = new int[huge];
        std::cout << "Allocated?!\n";
        delete[] p;
    }
    catch (const std::bad_alloc& e)
    {
        std::cout << "new failed: " << e.what() << '\n';
    }

    // 2. nothrow new returns nullptr instead of throwing
    int* q = new (std::nothrow) int[huge];
    if (q == nullptr)
        std::cout << "nothrow new returned nullptr\n";
    delete[] q;      // safe even if q is nullptr

    return 0;
}

Output (g++ 15 on Linux; the text returned by what() is implementation-defined):

new failed: std::bad_alloc
nothrow new returned nullptr

So checking if (p == nullptr) after a normal new is pointless. That check is a habit carried over from C's malloc().


new/delete vs malloc()/free()

C++ still supports the C functions std::malloc() and std::free() from <cstdlib>. But new is not just "malloc() with different syntax". The key difference: new creates objects, malloc() only hands out raw bytes.

#include <iostream>
#include <string>
#include <cstdlib>   // std::malloc, std::free

int main()
{
    // new: allocates AND constructs the std::string
    std::string* s1 = new std::string("Hello from new");
    std::cout << *s1 << " (length " << s1->size() << ")\n";
    delete s1;      // destroys the string, then frees memory

    // malloc: only raw bytes, no object is created
    int* nums = static_cast<int*>(std::malloc(3 * sizeof(int)));
    if (nums != nullptr)
    {
        nums[0] = 1; nums[1] = 2; nums[2] = 3;   // fine for a simple type like int
        std::cout << nums[0] + nums[1] + nums[2] << '\n';
        std::free(nums);
    }
    return 0;
}

Output:

Hello from new (length 14)
6

If we had used malloc(sizeof(std::string)) and then treated that memory as a string, we would have undefined behavior, because no std::string object was ever constructed there. Its internal pointer and length would be garbage.

Pointnew / deletemalloc() / free()
What is it?Operator (part of the language)Library function
SizeComputed by the compiler from the typeWe pass the number of bytes (sizeof)
Return typeCorrectly typed pointer (int*)void*; C++ requires a cast
Constructors / destructorsCalledNot called
On failureThrows std::bad_allocReturns nullptr
Can be overloaded per class?Yes (operator new)No
ResizeNo built-in resizerealloc() (only safe for simple C-like types)

In C++ code, use new/delete (or better, the tools in the "Modern Advice" section below). Use malloc() only when talking to C libraries that require it.


The Three Classic Bugs

Manual memory management gives us power, and with it three classic bugs. Every C++ interview expects you to know them.

1. Memory Leak

A memory leak happens when heap memory is no longer reachable (we lost every pointer to it) but was never freed.

#include <iostream>

void process()
{
    int* data = new int[100];
    data[0] = 1;
    std::cout << "Processing... " << data[0] << '\n';
    // forgot delete[] data;  -> the 400 bytes are never returned
}

int main()
{
    process();
    return 0;
}

When process() returns, the local pointer data is destroyed, but the 100 integers on the heap are not. Nothing points to them any more, so they can never be freed.

Built with -fsanitize=address, the leak checker reports it when the program exits (trimmed):

Processing... 1

==1062==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 400 byte(s) in 1 object(s) allocated from:
    #0 ... in operator new[](unsigned long)
    #1 ... in process() leak.cpp:5
    #2 ... in main leak.cpp:13

SUMMARY: AddressSanitizer: 400 byte(s) leaked in 1 allocation(s).

The operating system reclaims all of a process's memory when it exits, so a small leak in a short program is harmless in practice. The real danger is in programs that run for days (servers, games, operating system services): if process() were called a million times, it would leak 400 MB.

Another common way to leak is to overwrite the only pointer:

int* p = new int(1);
p = new int(2);     // the first int is now unreachable: leaked
delete p;           // frees only the second one

2. Dangling Pointer (Use-After-Free)

A dangling pointer is a pointer that still holds the address of memory that has already been freed (or of an object whose lifetime has ended).

#include <iostream>

int main()
{
    int* p = new int(10);
    delete p;               // memory returned, but p still holds the old address

    std::cout << *p << '\n';   // use-after-free: undefined behavior
    return 0;
}

Without any special flags, this program might print 10, some garbage number, or crash. That's what undefined behavior means: the language gives no guarantee at all, and "it printed 10 on my machine" proves nothing. With AddressSanitizer we get a clear report (trimmed):

ERROR: AddressSanitizer: heap-use-after-free on address 0x7bd5041e0010
READ of size 4 at 0x7bd5041e0010 thread T0
    #0 ... in main uaf.cpp:8
freed by thread T0 here:
    #1 ... in main uaf.cpp:6
previously allocated by thread T0 here:
    #1 ... in main uaf.cpp:5

Dangling pointers also come from two pointers sharing one block:

int* a = new int(5);
int* b = a;      // b and a point to the same int
delete a;
a = nullptr;     // a is safe now ...
// ... but b is still dangling!

Setting a pointer to nullptr after delete helps, but it only fixes that pointer, not its copies. The real fix is to have one clear owner for each block of memory.

3. Double Delete

Calling delete twice on the same address is undefined behavior. On Linux with glibc, the program usually aborts at the second delete (often with a message such as free(): double free detected in tcache 2), and AddressSanitizer reports attempting double-free. But there is no guarantee of a crash: in larger programs a double delete can silently corrupt the heap and cause a crash much later, far from the real bug.

int* p = new int(3);
delete p;
delete p;        // undefined behavior: double free

Note that delete nullptr is always safe, which is another reason to set pointers to nullptr after deleting them.

BugCauseTypical symptomPrevention
Memory leakLost the last pointer without deleteMemory use keeps growingEvery new has exactly one matching delete; prefer RAII
Dangling pointerUsing memory after deleteGarbage values, random crashesSet to nullptr; one clear owner
Double deleteFreeing the same block twiceCrash / heap corruptionSet to nullptr; one clear owner
Mismatched deletenew[] with delete, etc.Crash, missing destructor callsMatch the forms exactly

Tip: while learning, compile with g++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined. AddressSanitizer catches all four bugs above with the exact line numbers.


Dynamic 2D Arrays

Suppose the number of rows and columns is only known at run time. There are two common approaches.

Approach 1: Array of Row Pointers

We allocate an array of int* (one pointer per row), and then allocate each row separately. This uses the pointer to pointer idea from the Pointers topic.

grid (int**)
   │
   ▼
┌──────┐      ┌───┬───┬───┬───┐
│  ●───┼────► │ 0 │ 1 │ 2 │ 3 │   row 0
├──────┤      └───┴───┴───┴───┘
│  ●───┼────► │ 4 │ 5 │ 6 │ 7 │   row 1
├──────┤      └───┴───┴───┴───┘
│  ●───┼────► │ 8 │ 9 │10 │11 │   row 2
└──────┘      └───┴───┴───┴───┘
#include <iostream>

int main()
{
    int rows = 3, cols = 4;

    // Step 1: an array of row pointers
    int** grid = new int*[rows];

    // Step 2: each row is its own array
    for (int i = 0; i < rows; i++)
        grid[i] = new int[cols];

    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            grid[i][j] = i * cols + j;

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
            std::cout << grid[i][j] << '\t';
        std::cout << '\n';
    }

    // Free in reverse order: first every row, then the row-pointer array
    for (int i = 0; i < rows; i++)
        delete[] grid[i];
    delete[] grid;

    return 0;
}

Output:

0	1	2	3	
4	5	6	7	
8	9	10	11	

The order of freeing matters. If we did delete[] grid; first, the row pointers stored inside it would be gone, and we could never free the rows (a leak). Reading grid[i] after that would also be a use-after-free.

This approach allows rows of different lengths (a jagged array), but it costs rows + 1 separate allocations, and the rows may be scattered around memory.

Approach 2: One Contiguous Block

We can store all rows × cols elements in a single 1D array and compute the position ourselves: element (i, j) is at index i * cols + j. This is exactly how a normal 2D array is laid out (row-major order).

#include <iostream>

int main()
{
    int rows = 3, cols = 4;

    int* grid = new int[rows * cols]{};   // one contiguous block, all zeros

    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            grid[i * cols + j] = (i + 1) * (j + 1);   // element (i, j)

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
            std::cout << grid[i * cols + j] << '\t';
        std::cout << '\n';
    }

    delete[] grid;      // one allocation, one delete[]
    return 0;
}

Output:

1	2	3	4	
2	4	6	8	
3	6	9	12	

One allocation, one delete[], and better cache performance because the elements are next to each other. This is the approach most high-performance libraries use.


Worked Example: A Growable Array

A heap array cannot change its size. To "grow" it, we must allocate a bigger block, copy the old elements over, free the old block, and switch the pointer. Let's build this step by step. This is the core idea behind std::vector, which we'll meet in the vector topic.

We keep two numbers: size (how many elements are in use) and capacity (how many fit in the current block). When they become equal, we double the capacity.

#include <iostream>

// Appends value to a dynamic array, growing it when it is full.
// arr, size and capacity are passed by reference so the caller sees the changes.
void pushBack(int*& arr, int& size, int& capacity, int value)
{
    if (size == capacity)
    {
        int newCapacity = (capacity == 0) ? 1 : capacity * 2;
        int* bigger = new int[newCapacity];

        for (int i = 0; i < size; i++)   // copy old elements
            bigger[i] = arr[i];

        delete[] arr;                    // free the old block
        arr = bigger;                    // point to the new block
        capacity = newCapacity;
        std::cout << "  (grew to capacity " << capacity << ")\n";
    }
    arr[size] = value;
    size++;
}

int main()
{
    int* arr = nullptr;
    int size = 0, capacity = 0;

    for (int v = 10; v <= 60; v += 10)
    {
        std::cout << "push " << v << '\n';
        pushBack(arr, size, capacity, v);
    }

    std::cout << "Contents:";
    for (int i = 0; i < size; i++)
        std::cout << ' ' << arr[i];
    std::cout << "\nsize = " << size << ", capacity = " << capacity << '\n';

    delete[] arr;
    return 0;
}

Output:

push 10
  (grew to capacity 1)
push 20
  (grew to capacity 2)
push 30
  (grew to capacity 4)
push 40
push 50
  (grew to capacity 8)
push 60
Contents: 10 20 30 40 50 60
size = 6, capacity = 8

Notice the parameter int*& arr: a reference to a pointer (from the References topic). The function must change the caller's pointer to point to the new block. If we wrote int* arr, the function would only change its own copy, and main() would keep using the freed block (a dangling pointer).

Why double instead of adding 1 each time? Copying costs time proportional to the current size. If we grew by 1, pushing n elements would copy 1 + 2 + ... + (n − 1) elements, which is O(n²). With doubling, the total copying is less than 2n, so each push costs O(1) amortized. This is a favourite interview question.


Modern Advice: Avoid Raw new/delete

Everything in this topic is important to understand, because it explains how C++ really works underneath. But in modern C++ code (C++11 and later), we rarely write new and delete by hand. The C++ Core Guidelines say: avoid calling new and delete explicitly.

Instead, we let an object own the memory and free it automatically when the object goes out of scope. This technique is called RAII (Resource Acquisition Is Initialization), and we'll see how it works in the Constructors & Destructors topic.

Instead of ...Prefer ...Covered in
new int[n] / delete[]std::vector<int>vector
new char[n] for textstd::stringStrings
new T with a single ownerstd::unique_ptr<T> via std::make_unique (C++14)Smart Pointers
new T with shared ownershipstd::shared_ptr<T> via std::make_sharedSmart Pointers

These types cannot leak (they always free their memory), and they don't need a matching delete anywhere.


Common Mistakes

  • Forgetting delete, especially on early return paths or when an exception is thrown between new and delete.

  • Using delete instead of delete[] (or the reverse). Always match the form.

  • Using memory after delete, or keeping a second pointer to freed memory.

  • Deleting something that wasn't created with new, such as the address of a local variable: int x; delete &x; is undefined behavior.

  • Checking for nullptr after a normal new. It throws instead; only new (std::nothrow) returns nullptr.

  • Reading new int or new int[n] before assigning. Their values are indeterminate. Use {} if you want zeros.

  • Returning the address of a local variable from a function instead of heap memory. The local dies when the function returns, so the pointer dangles immediately.

  • Freeing a 2D array in the wrong order (outer array before the rows).


Interview / GATE Questions

1. What is the difference between new and malloc()?

new is an operator that computes the size from the type, returns a correctly typed pointer, calls the constructor, and throws std::bad_alloc on failure. malloc() is a library function that takes a byte count, returns void*, does not construct any object, and returns nullptr on failure. Memory from new must be freed with delete; memory from malloc() with free().

2. What happens if you use delete on memory allocated with new[]?

Undefined behavior. For class types, typically only the first element's destructor runs and the allocator may receive the wrong address, which can crash or corrupt the heap. It might seem to "work" for int, but it is still undefined behavior. Use delete[].

3. Is delete p; safe when p is nullptr?

Yes. Deleting a null pointer (with delete or delete[]) does nothing. There is no need to write if (p) delete p;.

4. What is a memory leak, and how can you detect one?

A leak is heap memory that was never freed and that the program can no longer reach. Tools such as AddressSanitizer/LeakSanitizer (-fsanitize=address), Valgrind (valgrind --leak-check=full) and Visual Studio's diagnostic tools report leaks with the allocation site. The best prevention is RAII types such as std::vector and std::unique_ptr.

5. What is printed? int* p = new int[3]{1}; std::cout << p[0] + p[1] + p[2];

1. The brace list initializes p[0] to 1 and value-initializes the rest to 0, so the sum is 1 + 0 + 0. (Remember to delete[] p;.)

6. Why does a dynamic array grow by doubling its capacity instead of by a fixed amount?

Each growth copies all current elements. With doubling, the total copying for n insertions is less than 2n, giving O(1) amortized time per insertion. Growing by a constant k gives about n²/(2k) copies in total, i.e. O(n) per insertion on average.

7. In the row-pointer approach for an r × c 2D array, how many calls to new are made, and how many delete[] calls are needed?

r + 1 of each: one for the array of row pointers and one for each of the r rows. The contiguous approach needs just one of each.


Summary

  • Dynamic memory comes from the heap (free store). Its size is chosen at run time and it lives until we free it.

  • new T allocates and constructs one object; delete p destroys it and frees the memory.

  • new T[n] allocates an array; it must be freed with delete[] p.

  • new int leaves the value indeterminate; new int{} gives 0; new int{7} gives 7.

  • A failed new throws std::bad_alloc; new (std::nothrow) returns nullptr instead.

  • new calls constructors and is type-safe; malloc() just returns raw bytes.

  • The classic bugs are memory leaks, dangling pointers, double delete and mismatched delete. AddressSanitizer finds all of them.

  • In modern C++, prefer std::vector, std::string and smart pointers over raw new/delete.