Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 171 ยท Pointers, References and Memory

Dynamic Memory: new and delete

Learn C++ dynamic memory - heap allocation with new and delete, new[] and delete[], memory leaks, double delete, dangling pointers and why modern code avoids raw new.

So far, almost every object you've created had its lifetime decided by where you declared it. A local variable lives until the end of its block; a global lives for the whole program. That's simple and fast, but sometimes you need an object whose lifetime you control yourself: one that outlives the function that created it, whose size is only known at run time, or that's too big for the stack. For that, C++ lets you allocate objects on the heap (the standard calls it the free store) with new and give them back with delete.

This lesson teaches new and delete properly, because you'll read them in countless codebases and libraries, and because understanding them is the only way to understand what smart pointers and containers do for you. You'll also see the four classic bugs (leaks, double deletes, dangling pointers and mismatched delete[]), and why modern C++ guidelines say: don't write raw new and delete in application code. By the end you'll be ready for std::unique_ptr, the tool that replaces them.

Stack vs heap, briefly

Local variables live in automatic storage, usually on the call stack. Creating one is nearly free (the stack pointer moves), and destruction happens automatically at the end of the scope. The catch: the size must be known at compile time, the stack is small (often 1โ€“8 MB), and the object dies with its scope.

The heap is a large pool of memory managed at run time. You ask for memory with new, get back a pointer, and the object lives until you delete it, regardless of scopes. That flexibility costs a little speed (allocation has to find a free block) and a lot of responsibility (you must free it exactly once). Memory Layout: Stack, Heap and Objects looks at these regions in more detail.

new and delete for single objects

new T allocates memory for one T, constructs the object there and returns a T*. new T(args) or new T{args} passes constructor arguments. delete p runs the destructor and frees the memory.

C++ Allocating and freeing one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that the robot built inside build() survived after the function returned. That's the whole point of the heap, and also the whole danger: nothing destroys it automatically. Some code, somewhere, must call delete exactly once.

Initialization follows the usual rules. new int leaves the int uninitialized (garbage), while new int{} or new int() value-initializes it to 0. For class types, new T calls the default constructor either way.

Deleting a null pointer is always safe and does nothing, so you never need if (p) delete p;.

new[] and delete[] for arrays

To allocate an array whose size is decided at run time, use new T[n]. It returns a pointer to the first element. You must free it with delete[], not delete.

C++ A run-time sized array with new[]

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The runtime remembers how many elements to destroy for delete[], but you have no portable way to ask it: the size is your job to track. That's one of the reasons this pattern is almost always better written as std::vector<int> squares(count);, which tracks the size, frees itself and checks bounds with at().

Always match the forms: new with delete, new[] with delete[]. Using delete on memory from new[] (or the reverse) is undefined behavior. With class types it typically destroys only the first element or corrupts the heap. GCC can sometimes warn (-Wmismatched-new-delete), but not when the allocation and the delete are far apart.

The four classic bugs

Manual memory management goes wrong in four characteristic ways. Each one compiles without errors.

1. Memory leaks

A leak happens when the last pointer to a heap object is lost before delete is called. The memory stays allocated until the program ends. One leak is harmless; a leak inside a loop or in a server that runs for weeks eventually exhausts memory.

C++
void process(int id) {
    auto* buffer = new char[4096];
    if (id < 0) {
        return;              // LEAK: early return skips the delete
    }
    // ... use buffer ...
    delete[] buffer;
}

Early returns, break, and especially exceptions all skip the delete. Writing delete on every path is fragile; any new early return reintroduces the leak.

2. Double delete

Calling delete twice on the same pointer is undefined behavior. It usually corrupts the allocator's internal bookkeeping, and the crash may happen much later, far from the bug. It's common when two parts of a program each think they own the object.

3. Use after free (dangling pointers)

After delete p, the pointer p still holds the old address. Reading or writing through it is undefined behavior, and other pointers to the same object (copies made earlier) dangle too. Setting p = nullptr after deleting helps only for that one variable.

4. Mismatched forms

delete on new[] memory, free() on new memory, or delete on a pointer that never came from new (like the address of a local) are all undefined behavior.

The program below demonstrates the first bug safely. It replaces the global operator new and operator delete with counting versions (a legitimate C++ technique), so you can watch a leak happen.

C++ Counting allocations to spot a leak

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Two calls threw, so two ints were never freed, and the counter ends at 2. (Throwing an exception allocates memory of its own, but not through operator new, so the count reflects only our leaks.) The last_allocation global is there because the optimizer is allowed to remove an allocation whose result is never really used; without it, GCC at -O1 can drop the leaked new int entirely and the leak vanishes from the count. In a long-running program, every rejected request would leak a little more.

Why delete is so hard to get right: ownership

All four bugs come from one question that raw pointers can't answer: who owns this object? An int* looks the same whether it points to a local, a heap object you must delete, a heap object someone else will delete, or an element of an array. The type says nothing about responsibility.

The C++ answer is RAII (Resource Acquisition Is Initialization): give ownership to an object whose destructor frees the resource. Destructors run automatically when an object goes out of scope, on every path: normal return, early return, break and exceptions. You'll study RAII in Destructors and RAII; the standard library already gives you the RAII types you need:

Instead ofโ€ฆ Useโ€ฆ
new T[n] / delete[] std::vector<T> (or std::array<T, N> when the size is fixed)
new char[n] for text std::string
new T with one owner std::unique_ptr<T> via std::make_unique<T>(...)
new T shared by several owners std::shared_ptr<T> via std::make_shared<T>(...)

Here is leaky rewritten in the modern style. There's no delete to forget:

C++ The same code with RAII: no leaks on any path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every Tracker is freed, including the ones whose function threw. Notice that the "freed" message for ids 2 and 4 appears before the catch handler's message: during stack unwinding, destructors run as the exception leaves safe.

Allocation failure

If new can't get memory, it throws std::bad_alloc rather than returning null. So checking if (p == nullptr) after a plain new is pointless. There's a variant, new (std::nothrow) T, that returns nullptr on failure instead, for code that can't use exceptions. On desktop systems with virtual memory, allocation rarely fails outright; in embedded systems it's a real concern.

C++
#include <new>

int* big = new (std::nothrow) int[1'000'000];
if (big == nullptr) {
    // handle the failure without exceptions
}
delete[] big;

Mixing new/delete with malloc/free

C++ inherited malloc and free from C, and both families work on the heap, but they are not interchangeable:

  • new calls a constructor and delete calls the destructor; malloc only reserves raw bytes and free only releases them. Memory from malloc holds no live object until you construct one in it.
  • new throws std::bad_alloc on failure; malloc returns nullptr.
  • new computes the size from the type and returns a typed pointer; malloc takes a byte count and returns void*.
  • Releasing memory with the wrong partner (free on new'd memory, delete on malloc'd memory, or delete on new[]) is undefined behavior: destructors are skipped, or the allocator's bookkeeping is corrupted.
C++
std::string* a = new std::string("hi");
delete a;                       // correct pair

std::string* b = (std::string*)std::malloc(sizeof(std::string));
// *b is NOT a valid string: no constructor ran. Using it is undefined behavior.
std::free(b);                   // correct pair, but never constructed an object

Pick one family per allocation and keep to it. In modern C++ the answer is usually neither: use containers and smart pointers. See C and C++ for the other differences between the languages.

When you'll still see new and delete

Raw new and delete haven't disappeared. You'll meet them:

  • In older codebases written before C++11, and in code written by people who learned C++ that way.
  • Inside the implementation of RAII types: containers, smart pointers, custom allocators and memory pools. Someone has to call the low-level operations; the point is to do it in one well-tested class, not throughout the program.
  • With frameworks that take ownership of raw pointers through their own conventions (for example, some GUI libraries where a parent widget deletes its children).
  • Placement new (new (address) T(...)), which constructs an object in memory you already have. It's an advanced tool used by containers like std::vector and std::optional.

In code you write day to day, a good rule is: if you type new, you should be able to explain why std::make_unique, std::make_shared or a container wasn't possible. If you type delete, something has probably gone wrong.

Compile your experiments with -fsanitize=address when you can. AddressSanitizer reports leaks, double deletes, use-after-free and mismatched delete/delete[] with the exact lines involved. See Undefined Behavior and Memory Safety.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement correctly frees int* data = new int[100];?

    Memory from new[] must be freed with delete[]. Plain delete or free on it is undefined behavior.
  2. 2. A function allocates with new, then throws an exception before reaching delete. What happens to the object?

    Stack unwinding destroys local objects, but a raw pointer's destructor does nothing. The heap object leaks unless an RAII owner like unique_ptr holds it.
  3. 3. What does plain new do when it cannot allocate memory?

    Ordinary new throws std::bad_alloc. Only new (std::nothrow) returns nullptr on failure.
  4. 4. int* p = new int{5}; int* q = p; delete p; p = nullptr; What is true about q now?

    Setting p to nullptr only changes p. q still holds the old address of memory that was freed.
  5. 5. What is the modern replacement for new T[n] / delete[] when n is known only at run time?

    std::vector owns a run-time-sized array, tracks its size and frees it automatically. std::array needs a compile-time size.

Summary

  • Heap (free-store) objects live until you destroy them, independent of scope. new T(args) creates one and returns a T*; delete p destroys it.
  • new T[n] creates a run-time-sized array; free it with delete[]. Mixing new/delete[] or new[]/delete is undefined behavior.
  • new int is uninitialized; new int{} is zero. delete nullptr is a safe no-op. Plain new throws std::bad_alloc on failure.
  • The classic bugs: leaks (lost pointers, early returns, exceptions), double delete, use after free, mismatched forms. They all compile.
  • Raw pointers don't express ownership. RAII types do: std::vector, std::string, std::unique_ptr, std::shared_ptr.
  • In modern application code, avoid writing new and delete yourself; they belong inside well-tested RAII classes.

Next: Smart Pointers: std::unique_ptr, the owning pointer that deletes for you and costs nothing extra.