Course outline · 0% complete

0/27 lessons0%

Course overview →

Stack vs Heap, new and delete

lesson 6-1 · ~12 min · 15/27

Quiz

Warm-up from lesson 5-1: `int* p = &x; *p = 99;` does what?

This unit is the heart of C++'s reputation, good and bad. Where a value lives decides how long it exists, how fast it is to allocate, and who must clean it up. Every segfault war story, every garbage-collector pause in other languages, and a large share of systems-interview questions trace back to the distinction on this page.

Two places your data can live

The stack. Every function call gets a stack frame: a slab of memory holding its parameters and local variables. When the function returns, the frame is popped and every variable in it dies instantly. All the locals you have written so far lived here. Stack memory is automatic and extremely fast, but small (a few MB) and tied to scope.

The heap. A big pool of memory you request at run time. Heap data survives until you explicitly free it, no matter how many functions return in the meantime. The price: you are the garbage collector.

int* makeCounter() {
    int local = 0;          // stack: dies when makeCounter returns
    int* h = new int(0);    // heap: survives the return
    return h;               // caller receives the address
}

new int(0) allocates one int on the heap, initializes it to 0, and returns its address. Later, someone must call delete on that address, or the memory is lost until the program exits: a memory leak.

Python note: every Python object lives on a heap, and the garbage collector frees it for you. C++ gives you the choice, and the responsibility.

stackheapmain() framemakeCounter()newnewframes come and go with callsblocks live until you delete
Stack frames appear on call and vanish on return (watch makeCounter's frame). Heap blocks created with new stay put until delete, even after their creator returned.

Code exercise · cpp

Run this full new / use / delete cycle for a single heap int and for a heap array. Note delete[] for arrays.

Code exercise · cpp

Your turn: the heap int is allocated but never freed — a leak. Add the delete, then set the pointer to nullptr afterwards (so any later accidental dereference fails loudly instead of touching freed memory). Output should be 15 then freed.

Quiz

A function calls `new int[1000]` every time it runs and never calls delete[]. What is this bug called, and what happens?

Code exercise · cpp

Your turn. Read n, allocate a heap array of n ints, fill element i with i * i, print them one per line, then free the array with the correct delete form. Input is 5.