C++ Lesson 27 โ€“ Memory Management | Dataplexa
Advanced C++ ยท Lesson 27

Memory Management

Every variable you have used so far lived in a place you never had to think about. Now it is time to look behind the curtain. Your program has two places to keep data: the stack, which manages itself, and the heap, which you manage yourself. The stack is easy and automatic. The heap is powerful and dangerous. This lesson teaches you where your data lives, how to ask for heap memory, and how to give it back โ€” because in C++, memory you forget to return is memory lost.

1. Two Places for Data: Stack and Heap

Think of the stack as a pile of plates: every time a function is called, its local variables are placed on top, and when the function returns, they are lifted off again โ€” automatically, in perfect order. Nothing is ever forgotten, and nothing lasts longer than its function. The heap is a big open warehouse: you ask for a shelf of any size, you keep it for as long as you like, and you must hand it back yourself when you are done. The stack is fast and safe; the heap is flexible and long-lived. Most of your variables belong on the stack. The heap is for data whose size you only know at run time, or that must outlive the function that created it.

Aspect Stack Heap
Who manages itThe compiler, automaticallyYou, with new and delete
LifetimeUntil the function returnsUntil you delete it
Size limitSmall โ€” a few megabytesLarge โ€” as much as the machine has
CostAlmost freeSlower to ask for and to free
Use it forLocal variables, small and short-livedData whose size is known only at run time, or that outlives a function

2. new and delete โ€” Asking for Heap Memory

To get heap memory you write new. It asks the system for room, and hands you back a pointer to it: int* p = new int(42); creates one int on the heap, sets it to 42, and gives you its address. When you are done, you hand the room back with delete: delete p;. The golden rule is one delete for every new โ€” every room you take, you return. After deleting, set the pointer to nullptr so nobody can use the freed room by mistake.

Code story: Here is the simplest heap program. One integer is created on the heap with new, read through its pointer, and then handed back with delete. Watch the value arrive, and watch the pointer become empty afterwards.

#include <iostream>
using namespace std;

int main() {
    int* p = new int(42);
    cout << "Value: " << *p << endl;
    delete p;
    p = nullptr;
    cout << "Memory returned." << endl;
    return 0;
}
Value: 42
Memory returned.

What just happened? The new created an int on the heap and returned its address into p. The program read the value through the pointer, then deleted the memory and set p to nullptr โ€” the safe habit from Lesson 25. Nothing was leaked, nothing is dangling: p is empty, and the heap is exactly as it was before. If you had skipped the delete, the program would still print the same two lines โ€” and silently leak four bytes. That silence is the whole subject of Section 4.

3. Arrays on the Heap โ€” new[] and delete[]

A single value is only the beginning. The real reason for the heap is arrays whose size you do not know until the program runs: new int[5] asks for five ints in a row, and delete[] โ€” with square brackets โ€” gives the whole row back. The brackets matter: delete alone frees only the first element's bookkeeping and leaves the rest behind, which is a bug that may not show up until much later. One rule to remember: new goes with delete, and new[] goes with delete[]. Never mix them.

Code story: Now an array, sized at run time. Five numbers are created on the heap, added up through the pointer, and the whole row is handed back with delete[]. Watch the sum print โ€” and notice that the array works exactly like the stack arrays from Lesson 11.

#include <iostream>
using namespace std;

int main() {
    int* nums = new int[5]{1, 2, 3, 4, 5};
    int sum = 0;
    for (int i = 0; i < 5; i++) sum += nums[i];
    cout << "Sum: " << sum << endl;
    delete[] nums;
    nums = nullptr;
    return 0;
}
Sum: 15

What just happened? The new[] created five ints on the heap, and the pointer nums reaches them with the same square-bracket indexing you already know. After the sum, delete[] returns the whole row โ€” brackets included โ€” and the pointer is set to nullptr. In Lesson 24, the Library used exactly this kind of ownership: it news books and deletes them in its destructor. Lesson 28 will build on this with arrays and objects created at run time.

4. Memory Leaks โ€” The Slow Disappearing Act

A memory leak is heap memory that was allocated and never freed. The program still works โ€” leaks do not crash your program on the spot. What they do is worse: each leaked block stays held forever, the program's memory grows a little with every call, and one day the machine runs out. A leak in a function that runs once is a few bytes. A leak in a loop that runs a million times is a crash in the middle of the night. The only defence is discipline: every new gets a delete, in the same place you can see it.

Code story: Here is a leak, hiding in plain sight. A function builds an array, adds it up, and returns the answer โ€” but never frees the array. Watch the program print the right answer anyway. That is the trap: a leak is invisible in the output.

#include <iostream>
using namespace std;

int makeTotal() {
    int* nums = new int[3]{10, 20, 30};
    int total = nums[0] + nums[1] + nums[2];
    return total;   // LEAK: nums is never deleted
}

int main() {
    cout << "Total: " << makeTotal() << endl;
    return 0;
}
Total: 60

What just happened? The answer is correct โ€” 60 โ€” and the array of three ints is still sitting on the heap, held forever, with no pointer left to find it. The function returned, its local pointer vanished, and the memory became unreachable: allocated, but no one can use it or free it. Run makeTotal() in a loop a million times and you leak 12 million bytes. The fix is one line โ€” delete[] nums; before the return โ€” and Section 5 shows a pattern that makes the fix automatic.

5. RAII โ€” Let the Object Own the Memory

There is a better way than remembering to write delete. RAII โ€” Resource Acquisition Is Initialization โ€” means the object owns the memory: it asks for it in its constructor and gives it back in its destructor. Because a destructor always runs when an object goes out of scope โ€” even when an exception is thrown โ€” the memory is always returned. You met the destructor in Lesson 16, and the Library in Lesson 24 already used this idea: it owned its books and deleted them in its destructor. Lesson 36 will show you the ready-made version of this pattern, the smart pointer.

Code story: Here is the fix, and it is the most important pattern in C++. The object owns the memory: it asks for it in its constructor and gives it back in its destructor. Watch the destruction happen on its own when the object goes out of scope.

#include <iostream>
using namespace std;

class Buffer {
private:
    int* data;
    int size;
public:
    Buffer(int s) : size(s) {
        data = new int[size];
        cout << "Buffer of " << size << " created." << endl;
    }
    void set(int i, int v) { data[i] = v; }
    int get(int i) { return data[i]; }
    ~Buffer() {
        delete[] data;
        cout << "Buffer destroyed." << endl;
    }
};

int main() {
    Buffer b(3);
    b.set(0, 10);
    b.set(1, 20);
    b.set(2, 30);
    cout << "Sum: " << b.get(0) + b.get(1) + b.get(2) << endl;
    return 0;
}
Buffer of 3 created.
Sum: 60
Buffer destroyed.

The rule to remember: whoever news the memory should own it โ€” and the owner should delete it in its destructor. Then no one has to remember anything, and no leak can slip through.

6. Common Mistakes with Memory Management

Mistake What happens Fix
Forgetting deleteThe memory leaks โ€” held forever, never reusableOne delete for every new, in the same place you can see it
Using delete instead of delete[] on an arrayOnly part of the array is freed, and the rest leaksnew goes with delete, new[] goes with delete[]
Using memory after deleteA dangling pointer reads or writes freed memorySet the pointer to nullptr right after deleting it
Deleting the same pointer twiceThe second delete corrupts the heapDelete once, then set the pointer to nullptr
Returning a pointer to a local variableThe local dies when the function returns, and the pointer danglesReturn heap memory with new, or return by value

Practice โ€” Memory Management

Try these on your own. Compile and run each one.

  1. Allocate a single int with new, set it to 42, print it, then delete it and set the pointer to nullptr.
  2. Allocate an array of 5 doubles with new[], fill it, print the average, then delete[] it.
  3. Write a function that allocates an array of n ints and returns the pointer. Call it, use the array, then delete[] it in main.
  4. Write a small class that owns a single int: its constructor news the int, its destructor deletes it, and it has get() and set() functions.

Where does memory from new live?


What must you do with memory you got from new?


What is a memory leak?


Fill in the blanks โ€” type the missing word into the box.

Memory from new lives on the .


Return heap memory with when you are done with it.


An array made with new[] must be freed with .


Up Next

Dynamic Allocation

Next, allocating arrays and objects at run time.