Skip to content
dsa/roadmap
1.3 medium

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 call delete. 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

  1. Null dereference: *p when p == nullptr. Crash.
  2. Dangling pointer: using p after delete p. Random behaviour.
  3. Memory leak: losing the last pointer to heap memory, so it can never be freed.

Rule of thumb: every new has exactly one matching delete. After deleting, set the pointer to nullptr.

03Visualize

space play · ←→ step · r reset. The highlighted code line follows each step.

Loading visualizer…

04C++ code

Compiled and run with g++ -std=c++17; the output below is real. Type it out yourself before you copy it.

pointers.cpp25 lines · C++17
#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;
}
Expected output
x = 10, *p = 10
p points to x? yes
*q = 42
q is safely null
arr: 10 20 30 40

05Complexity

&x, *p, p->fieldO(1)
new / delete one objectO(1) (amortised; done by the allocator)
Stack memoryautomatic: freed when the function returns
Heap memorymanual: lives until delete

Linked lists, trees and graphs are built from heap nodes connected by pointers. Most bugs in linked lists, trees and graphs are pointer bugs in disguise.

06Watch

Introduction to pointers in C/C++

mycodeschool · 10:07

Why this one: The clearest 10-minute introduction to `&`, `*` and what a pointer really stores.

Pointers and dynamic memory: stack vs heap

mycodeschool · 17:25

Why this one: Explains stack vs heap with diagrams. This is exactly what the visualizer above animates.

07Interview & exam lens

Likely questions

  1. What is a pointer? Explain & and * with an example.
  2. Differentiate between stack and heap memory.
  3. What is a memory leak? Write code that causes one and fix it.
  4. What is a dangling pointer and how do you avoid it?

Common mistakes

  • Dereferencing nullptr or an uninitialised pointer, which crashes (segmentation fault).
  • Using memory after delete (dangling pointer). Set the pointer to nullptr right after.
  • new[] paired with delete instead of delete[].
  • Overwriting the only pointer to heap memory before deleting it, which leaks it forever.

08Quick check

  1. 1.What does this print?
    int x = 3;
    int* p = &x;
    *p = *p + 4;
    cout << x;
  2. 2.Memory from new is freed…
  3. 3.Which line causes a leak?
    int* p = new int(5);   // A
    p = new int(6);       // B
    delete p;             // C
  4. 4.For a pointer Node* n, n->data is the same as…

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 + 1 sets a = 11
  • prints 11 10
  • delete q frees the heap int (q is now dangling, so set it to nullptr)

🟡 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

  • Design Linked List mediumleetcode.com
    Hint

    The best pointer workout. Start with addAtHead and get; draw boxes and arrows on paper for every line.

  • Pointers in C (HackerRank) easyhackerrank.com
    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.

0/4 ticked

View as Markdown · Phase cheat sheet

Keyboard shortcuts

⌘K /
Search topics, glossary, cheat sheets
space
Play / pause the visualizer
← →
Step back / forward
r
Reset the visualizer
?
Show this help