Kodewick
Start learning →
Objects, pointers and references5 / 52

Objects, pointers and references

Lesson 5 of 52 · Part 2 · Arrays and linked lists · about 22 minutes

A node in C++ is a struct with a constructor, reached through a pointer and ->, made with new and freed with delete, after which pointers to it dangle; a reference lets a function change an outside variable.

The linked lists, trees and graphs in the rest of this course are nearly all made of small objects: each holds a number and "where the next one is". In C++ that small object is a struct, "where" is a pointer, and the object itself is put on the heap with new. This lesson gets those tools ready: how to define a node, how pointers differ from references, when what you new gets its delete, and which pointers you must not use any more.

A node: a struct with a constructor

A node of a linked list holds two things: a number, and the address of the next node.

1struct Node {2    int val;       // the number in this node3    Node* next;    // the address of the next node; nullptr if there is none4    Node(int v) : val(v), next(nullptr) {}   // the constructor5};
  • In C++ a struct and a class are almost the same; the one difference is that a struct's members are public by default. A node that only holds data is usually a struct.
  • Inside the struct you can write Node* next directly, not struct Node *next as in C.
  • The constructor Node(int v) : val(v), next(nullptr) {} sets both members at once with an initializer list. After Node a(3);, val is 3 and next is nullptr.
  • C++ writes the null pointer nullptr, not NULL.
main.cpp
1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10int main() {11    Node a(3);            // a node on the stack12    Node b(7);13    a.next = &b;          // a's next holds b's address14    cout << a.val << " " << b.val << "\n";15    cout << a.next->val << "\n";      // follow a.next to b16    cout << (b.next == nullptr ? "nothing after b" : "more after b") << "\n";17    return 0;18}
Output
3 7
7
nothing after b
Choose one

How does struct differ from class in C++?

Guess the outputA wrong guess is fine

Follow next twice. What does it print?

1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10int main() {11    Node a(4), b(5), c(6);12    a.next = &c;13    c.next = &b;14    cout << a.next->val << " " << a.next->next->val << "\n";15    return 0;16}

Pointers and ->

Node* p = &a; makes p hold a's address. *p is a itself, and (*p).val is a's val; that is written so often that C++ has a short form, p->val. A change made through p changes the object it points at.

stack

aNode3
bNode7
pNode*nullptr

whatever p holds the address of, p->val changes that one

(Each node's box shows only its val.)

main.cpp
1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10int main() {11    Node a(3), b(7);12    Node* p = &a;13    p->val = 30;          // the same as (*p).val = 3014    p = &b;15    p->val = 70;16    cout << a.val << " " << b.val << "\n";17    return 0;18}
Output
30 70
Guess the outputA wrong guess is fine

Two pointers start out pointing at the same node. What does it print?

1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10int main() {11    Node a(1), b(2);12    Node* p = &a;13    Node* q = p;14    q->val = 10;15    q = &b;16    q->val = 20;17    cout << a.val << " " << b.val << " " << p->val << "\n";18    return 0;19}
Fill inTap one to fill a blank; tap a blank to take it back

Fill the gap so that p points at b and the program prints 3 70.

1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10int main() {11    Node a(3), b(7);12    Node* p = ;13    p->val = 70;14    cout << a.val << " " << b.val << "\n";15    return 0;16}

new and delete: nodes on the heap

An object on the stack is gone when its function ends; the nodes of a list have to stay, and you don't know beforehand how many there will be. So nodes go on the heap with new:

  • new Node(3) takes a piece of heap memory big enough for a Node, runs the constructor, and gives you its address. No sizeof, and no setting the values yourself (C's malloc needs both).
  • delete p runs the destructor and gives that memory back.

stack

headNode*nullptr

heap

3Node
7Node
9Node

three nodes made with new on the heap, each in its own place; head is on the stack and points at the first

The three nodes are linked by next into 3 → 7 → 9. Walking them is nearly always written the same way: p starts at head, does p = p->next each time, and stops at nullptr.

p↓
3a
7b
9c
nullptr

a walk: p starts at head, p = p->next each time, stop at nullptr
main.cpp
1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10int main() {11    Node* head = new Node(3);12    head->next = new Node(7);13    head->next->next = new Node(9);14    for (Node* p = head; p != nullptr; p = p->next)15        cout << p->val << " -> ";16    cout << "nullptr\n";17 18    // done: delete them one by one. Remember the next one first, then delete this one19    int n = 0;20    while (head != nullptr) {21        Node* nxt = head->next;22        delete head;23        head = nxt;24        n++;25    }26    cout << "deleted " << n << " nodes\n";27    return 0;28}
Output
3 -> 7 -> 9 -> nullptr
deleted 3 nodes

Everything you new needs a delete, and every structure written by hand in this course gives its memory back at the end (with a loop like this one, or in a destructor). The order matters: delete head first and then read head->next, and you read memory that has already been given back.

Choose one

What does new Node(3) do that C's malloc(sizeof(Node)) doesn't?

Put in orderDrag, or use the arrows

Put the 3 lines of the loop in order: delete the list's 3 nodes one by one, then print 3.

  1. head = nxt;
  2. delete head;
  3. Node* nxt = head->next;
Should print
3

References: another name

int& r = n; makes r another name for n: changing r changes n. A reference is bound to one variable when it is made; it can't be bound to another later, and it can't be empty.

Its most common use is a function parameter. Without &, the function gets a copy, and a change to it doesn't get out; with &, the name in the function is the variable outside:

main.cpp
1#include <iostream>2using namespace std;3 4void by_value(int x) { x = x + 1; }   // changes a copy5void by_ref(int& x) { x = x + 1; }    // changes the one outside6 7int main() {8    int n = 5;9    int& r = n;10    r = 6;                 // that is n = 611    cout << n << "\n";12    by_value(n);13    cout << n << "\n";14    by_ref(n);15    cout << n << "\n";16    return 0;17}
Output
6
6
7
pointer Node* preference int& r
can it be emptyyes: nullptrno
can it point somewhere elseyes: p = &bno, always the same one
how you use it*p, p->valjust r
used forlinking nodes in lists and treesparameters: to change the caller's variable, or to avoid a copy (const vector<int>& v)

A pointer is a variable too, so it can have a reference: Node*& head is "another name for a Node* variable". When a function must change the caller's head (to add a node at the front of a list, say), the parameter is written like that. What happens without the &:

Guess the outputA wrong guess is fine

push_front's parameter has no &. What does it print?

1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10void push_front(Node* head, int v) {   // the & is missing11    Node* n = new Node(v);12    n->next = head;13    head = n;14}15 16int main() {17    Node* head = new Node(1);18    push_front(head, 2);19    push_front(head, 3);20    int count = 0;21    for (Node* p = head; p != nullptr; p = p->next)22        count++;23    cout << head->val << " " << count << "\n";24    delete head;25    return 0;26}
Exercise 1

Swap with references

Finish swap_int: both parameters are references; swap the values of the two variables outside.

It should print
7 3
exercise1.cpp
1#include <iostream>2using namespace std;3 4void swap_int(int& a, int& b) {5    // swap a and b6}7 8int main() {9    int x = 3, y = 7;10    swap_int(x, y);11    cout << x << " " << y << "\n";12    return 0;13}
Output
Press Run or Ctrl+Enter
Exercise 2

Add at the front

Finish push_front: new a node, make it point at the old head, then make head point at it. The parameter is Node*&, so it changes main's head. free_all is already written.

It should print
40 -> 30 -> 20 -> 10 -> nullptr
deleted 4
exercise2.cpp
1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10void push_front(Node*& head, int v) {11    // new a node, put it in front of head, point head at it12}13 14int free_all(Node* head) {15    int n = 0;16    while (head != nullptr) {17        Node* nxt = head->next;18        delete head;19        head = nxt;20        n++;21    }22    return n;23}24 25int main() {26    Node* head = nullptr;27    for (int i = 1; i <= 4; i++)28        push_front(head, i * 10);29    for (Node* p = head; p != nullptr; p = p->next)30        cout << p->val << " -> ";31    cout << "nullptr\n";32    cout << "deleted " << free_all(head) << "\n";33    return 0;34}
Output
Press Run or Ctrl+Enter

Dangling pointers

After delete p, p still holds the same address, but that memory is no longer yours. Such a pointer is a dangling pointer: reading or writing through it is a bug. It happens most easily when two pointers point at one node:

stack

pNode*nullptr
qNode*nullptr

heap

5Node

after delete both p and q still hold the old address: both dangle; only p is set to nullptr
main.cpp
1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10int main() {11    Node* p = new Node(5);12    Node* q = p;13    delete p;14    p = nullptr;15    cout << q->val << "\n";   // q still points at memory already given back16    return 0;17}
Output
heap-use-after-free

What happened: Stopped at line 15. This memory is no longer yours: it was deleted (or a vector or string grew and moved), or it belonged to a function that has returned.

Press Run: our C++ stops on the last cout and says it used heap memory that was already given back (heap-use-after-free). Real g++ doesn't stop; it may print 5, or some number nobody can predict. That is undefined behaviour, the hardest kind of bug to find.

Another way to dangle: handing out the address of a local variable.

1Node* make() {2    Node n(5);3    return &n;     // wrong: n is gone when the function ends, the address dangles4}

A node that has to outlive its function is made with new.

Choose allPick all that apply

After these 4 lines run, which pointers are dangling? You can pick more than one.

1Node* p = new Node(1);2Node* q = p;3Node* r = new Node(2);4delete q;

With the STL

Every node you new yourself needs someone to remember its delete, and in a big program one gets missed. The standard containers do it for you:

  • list<int> is a doubly linked list: each element is a node made with new (holding the value, prev and next), and when the list is destroyed its destructor deletes every node.
  • vector<int> keeps its elements in one block on the heap (next lesson), which it also gets and gives back itself.

Do the same in your own structures: put the delete loop in the destructor ~List(). When the object leaves its scope (its closing brace), the destructor runs by itself and nothing is missed.

main.cpp
1#include <iostream>2#include <list>3using namespace std;4 5struct Node {6    int val;7    Node* next;8    Node(int v) : val(v), next(nullptr) {}9};10 11class List {12public:13    ~List() {                       // runs by itself when the object goes away14        int n = 0;15        while (head != nullptr) {16            Node* nxt = head->next;17            delete head;18            head = nxt;19            n++;20        }21        cout << "~List: deleted " << n << " nodes\n";22    }23    void push_front(int v) {24        Node* n = new Node(v);25        n->next = head;26        head = n;27    }28    void print() const {29        for (Node* p = head; p != nullptr; p = p->next)30            cout << p->val << " ";31        cout << "\n";32    }33 34private:35    Node* head = nullptr;36};37 38int main() {39    {40        List a;41        a.push_front(9);42        a.push_front(7);43        a.push_front(3);44        a.print();45    }                               // a is gone here: ~List runs by itself46    list<int> b;                    // the standard linked list: its nodes are made with new too, and it deletes them47    b.push_front(9);48    b.push_front(7);49    b.push_front(3);50    for (int x : b)51        cout << x << " ";52    cout << "\n";53    return 0;54}
Output
3 7 9 
~List: deleted 3 nodes
3 7 9 

(Don't copy a List like this one: two Lists would delete the same nodes. The hand-written structures in this course are never copied.)

written aswhere it liveswho gives it back
Node a(3);stackgone at the closing brace
new Node(3)heapyou, with delete
a hand-written List that deletes in its destructornodes on the heap~List(), by itself
vector<int>elements in one block on the heapthe vector
list<int>one heap node per elementthe list
unique_ptr<Node> (<memory>)heapitself, when no one uses it

new and delete of one node are O(1) each, but much slower than making an object on the stack (a free piece of heap has to be found), which is one reason a vector is often faster than a list.

In interviews: "Pointers vs references": a pointer can be null, can be pointed elsewhere, and needs * / ->; a reference must be bound when made, can't be rebound, and can't be null. "new vs malloc": new runs the constructor, needs no size, and throws bad_alloc when it fails; delete runs the destructor. "What is a dangling pointer": one that points at memory already freed (or at a local variable whose function has returned).

Guess the outputA wrong guess is fine

The destructor prints its own number. What does the program print?

1#include <iostream>2using namespace std;3 4struct Box {5    int id;6    Box(int i) : id(i) {}7    ~Box() { cout << id << " "; }8};9 10int main() {11    Box a(1);12    {13        Box b(2);14    }15    Box* c = new Box(3);16    delete c;17    cout << "| ";18    return 0;19}

Summary

Take-away

Nodes, pointers, references: the tools for hand-written structures

  • a struct Node with a constructor: new Node(3) makes it in one step
  • p->val is (*p).val; the null pointer is nullptr
  • everything you new needs a delete: remember next before you delete, or do it in a destructor
  • a reference is another name: Node*& head lets a function change the caller's head
  • after delete a pointer dangles: don't use it, set it to nullptr
1struct Node { int val; Node* next; Node(int v) : val(v), next(nullptr) {} };2Node* head = new Node(3);3for (Node* p = head; p != nullptr; p = p->next)4void push_front(Node*& head, int v);5Node* nxt = head->next; delete head; head = nxt;