Pointers, new/delete & the Heap
A pointer holds an address. new asks the heap for memory that lives until you delete it. Master this and linked lists become easy.
Rule of this site: Don't just watch: implement it yourself, then solve 2–3 problems.
02Mental model
A variable is a house; its value is the person living there; its address is the street address. A pointer is a slip of paper with an address written on it. It doesn’t hold the person, it tells you where to find them.
int x = 5; // a house with 5 in it
int* p = &x; // & = "address of": p holds x's address
*p = 10; // * = "go to that address": changes x to 10
Stack vs heap
- Stack: local variables. Created when a function starts, destroyed automatically when it returns. Fast, but small, and its size is fixed at compile time.
- Heap: memory you request at run time with
new. It stays alive until you calldelete. This is how we make data structures that grow while the program runs.
Node* n = new Node{7, nullptr}; // lives on the heap
delete n; // give it back
n = nullptr; // don't keep a stale address
Three classic bugs
- Null dereference:
*pwhenp == nullptr. Crash. - Dangling pointer: using
pafterdelete p. Random behaviour. - Memory leak: losing the last pointer to heap memory, so it can never be freed.
Rule of thumb: every
newhas exactly one matchingdelete. After deleting, set the pointer tonullptr.
03Visualize
space play · ←→ step · r reset. The highlighted code line follows each step.
04C++ code
Compiled and run with g++ -std=c++17; the output below is real. Type it out yourself before you copy it.
#include <iostream>
using namespace std;
int main() {
int x = 5;
int* p = &x; // p holds the address of x
*p = 10; // write through the pointer
cout << "x = " << x << ", *p = " << *p << "\n";
cout << "p points to x? " << (p == &x ? "yes" : "no") << "\n";
int* q = new int(42); // one int on the heap
cout << "*q = " << *q << "\n";
delete q; // give it back
q = nullptr; // never leave a dangling pointer
if (q == nullptr) cout << "q is safely null\n";
int n = 4;
int* arr = new int[n]; // array on the heap: size chosen at run time
for (int i = 0; i < n; i++) arr[i] = (i + 1) * 10;
cout << "arr: ";
for (int i = 0; i < n; i++) cout << *(arr + i) << " "; // pointer arithmetic
cout << "\n";
delete[] arr; // new[] needs delete[]
arr = nullptr;
}x = 10, *p = 10 p points to x? yes *q = 42 q is safely null arr: 10 20 30 40
05Complexity
&x, *p, p->field | O(1) |
|---|---|
new / delete one object | O(1) (amortised; done by the allocator) |
| Stack memory | automatic: freed when the function returns |
| Heap memory | manual: lives until delete |
Linked lists, trees and graphs are built from heap nodes connected by pointers. Every bug in Chapters 4–7 is a pointer bug in disguise.
06Watch
Introduction to pointers in C/C++
Why this one: The clearest 10-minute introduction to `&`, `*` and what a pointer really stores.
Pointers and dynamic memory: stack vs heap
Why this one: Explains stack vs heap with diagrams. This is exactly what the visualizer above animates.
Original class slides (Python, by the course's lecture authors):Linked List
07Exam lens
Likely questions
- What is a pointer? Explain
&and*with an example. - Differentiate between stack and heap memory.
- What is a memory leak? Write code that causes one and fix it.
- What is a dangling pointer and how do you avoid it?
Common mistakes
- Dereferencing
nullptror an uninitialised pointer, which crashes (segmentation fault). - Using memory after
delete(dangling pointer). Set the pointer tonullptrright after. new[]paired withdeleteinstead ofdelete[].- Overwriting the only pointer to heap memory before deleting it, which leaks it forever.
08Quick check
09Practice
🟢 Trace by hand
Draw the stack and heap after each line and say what is printed:
int a = 2;
int* p = &a;
int* q = new int(a * 5);
*p = *q + 1;
cout << a << " " << *q;
delete q;Show answer
- stack: a = 2, p → a; heap: (none)
q = new int(10): heap gets 10, q → it*p = *q + 1sets a = 11- prints 11 10
delete qfrees the heap int (q is now dangling, so set it tonullptr)
🟡 Implement it
Write int* makeArray(int n) that returns a heap array filled with 1..n, use it in main, print the sum, and free it correctly.
Hint
int* a = new int[n]; … delete[] a;. Check with g++ -fsanitize=address that there is no leak.
🔴 Solve problems
Hint
The best pointer workout. Start with addAtHead and get; draw boxes and arrows on paper for every line.
Hint
Modify two values through pointers. Warm-up for
*and&.
10Mastery checklist
Tick these honestly. When every box is ticked, the topic is marked complete.