Codiqo

Learn C++ · lesson 35 of 61 · about 8 minutes

new, delete and Their Problems

Search the dungeon cells with a vector sized at run time, and see why making memory with new and delete by hand causes leaks and crashes.

What you'll learn

  • Allocate with new and free with delete
  • Recognise leaks and dangling pointers
  • Prefer containers to new[]

The dungeon cells

Past the armoury is the dungeon. The hero types how many cells there are, then the gold found in each, so the adventure only knows how many numbers to keep once it's running. Old C++ code would make room with new int[cells] and had to remember delete[] afterwards. The adventure uses std::vector<int> loot(cells); instead: a vector with room for that many ints, which frees its own memory. Then it finds the richest cell, adds up the gold with std::accumulate, and adds it to gold. Zero or a negative number of cells means there's nothing to search.

The heap

new creates an object that lives until you delete it, on the heap:

int* p = new int(42); ... delete p;

Arrays use new int[n] and delete[] p. Every new needs exactly one matching delete, at exactly the right time. That's surprisingly hard, which is why modern C++ avoids writing it by hand.

Manual memory

#include <iostream>

int main() {
    int* xp = new int(120);
    *xp += 30;
    std::cout << *xp << "\n";
    delete xp;
    xp = nullptr;

    int n = 3;
    int* squares = new int[n];
    for (int i = 0; i < n; i++) squares[i] = (i + 1) * (i + 1);
    std::cout << squares[2] << "\n";
    delete[] squares;
}

Output

150
9

What goes wrong

| Bug | Cause |
|---|---|
| Leak | forgetting delete, or returning early before it |
| Dangling pointer | using memory after delete |
| Double delete | deleting the same memory twice |
| Wrong delete | delete instead of delete[] for arrays |

A std::vector or a smart pointer deletes for you, automatically and exactly once. That's the next lesson.

Tip

You'll meet new and delete in older code, so it's worth recognising them. In your own code, reach for std::vector (or a smart pointer, next lesson): they delete for you.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.