Memory and pointers · Lesson 12 of 21
Stack, heap, new and delete
Memory that frees itself, and memory you're responsible for.
10 minutes3 games
A program uses two areas of memory:
- The stack: ordinary local variables. Very fast, freed automatically when the scope ends (
}), but small (often a few megabytes). - The heap: a large area you allocate from at runtime with
new, which stays until you free it withdelete.
| Stack | Heap | |
|---|---|---|
How | int x = 5; | new int(5) |
Who frees | automatic at | you, with |
Speed | very fast | slower |
Size | small | large |
Lifetime | until the scope ends | until you free it |
C++
#include <iostream>
int main() {
int onStack = 10; // freed automatically
int* single = new int(42); // one int on the heap
int* many = new int[5]; // an array of 5 on the heap
for (int i = 0; i < 5; i++) many[i] = i * i;
std::cout << onStack << " " << *single << " " << many[4] << "\n";
delete single; // new -> delete
delete[] many; // new[] -> delete[]
single = nullptr; // don't leave it dangling
many = nullptr;
return 0;
}Spot the bug
This function runs every second on a server, and after days memory runs out. Why?
Quick question
A program needs an array of 50 million numbers. Where should it live?
Exercise
Allocate a heap array of n = 6 numbers, fill it with 1, 2, 4, 8, 16, 32 (each double the last), print their sum, and don't forget to free the memory.
Expected output: 63
C++
#include <iostream>
int main() {
int n = 6;
return 0;
}Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.