Objects, pointers and references
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
structand aclassare almost the same; the one difference is that astruct's members arepublicby default. A node that only holds data is usually astruct. - Inside the struct you can write
Node* nextdirectly, notstruct Node *nextas in C. - The constructor
Node(int v) : val(v), next(nullptr) {}sets both members at once with an initializer list. AfterNode a(3);,valis 3 andnextisnullptr. - C++ writes the null pointer
nullptr, notNULL.
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}
3 7 7 nothing after b
How does struct differ from class in C++?
struct defaults to public, class to private. Nodes that only hold data are usually written as struct; when you hide the insides (like the List at the end of this lesson), you write class.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}
a.next holds c's address, so a.next->val is 6; c.next holds b's address, so a.next->next->val is b's 5. A linked list is followed next by next like this, whatever order the nodes were defined in.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
aNode3bNode7pNode*nullptr(Each node's box shows only its val.)
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}
30 70
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}
q = p copies the address, so q and p point at the same a, and q->val = 10 changes a. Then q points at b and changes b; p hasn't moved and still points at a, so p->val is 10.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}
p is a Node*, so it holds an address: &b takes b's address. Writing b hands a whole node to a pointer, which doesn't compile; * only works on a pointer, and b isn't one.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 aNode, runs the constructor, and gives you its address. Nosizeof, and no setting the values yourself (C'smallocneeds both).delete pruns the destructor and gives that memory back.
stack
headNode*nullptrheap
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↓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}
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.
What does new Node(3) do that C's malloc(sizeof(Node)) doesn't?
malloc, new puts the node on the heap, and like malloc you have to give it back yourself (delete). What it adds: it works out the size and runs the constructor, so the node comes back already set up.Put the 3 lines of the loop in order: delete the list's 3 nodes one by one, then print 3.
head = nxt;delete head;Node* nxt = head->next;
3
delete head first and then read head->next, you're reading memory that has been given back: the engine here stops at that line with an error.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:
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}
6 6 7
pointer Node* p | reference int& r | |
|---|---|---|
| can it be empty | yes: nullptr | no |
| can it point somewhere else | yes: p = &b | no, always the same one |
| how you use it | *p, p->val | just r |
| used for | linking nodes in lists and trees | parameters: 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 &:
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}
head is passed by value: the head in the function is a copy, head = n changes only the copy, main's head still points at 1, and the list still has 1 node. The new 2 and 3 have no pointer to them, so they can never be deleted: a memory leak. With the parameter written Node*& head, it prints 3 3.Swap with references
✓Finish swap_int: both parameters are references; swap the values of the two variables outside.
7 3
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}
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.
40 -> 30 -> 20 -> 10 -> nullptr deleted 4
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}
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*nullptrqNode*nullptrheap
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}
heap-use-after-freeWhat 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.
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;
delete q gives that node back, so both dangle: delete doesn't fix p for you. r points at another node and is fine.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 withnew(holding the value,prevandnext), and when thelistis 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.
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}
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 as | where it lives | who gives it back |
|---|---|---|
Node a(3); | stack | gone at the closing brace |
new Node(3) | heap | you, with delete |
a hand-written List that deletes in its destructor | nodes on the heap | ~List(), by itself |
vector<int> | elements in one block on the heap | the vector |
list<int> | one heap node per element | the list |
unique_ptr<Node> (<memory>) | heap | itself, 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).
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}
delete c runs c's destructor and prints 3; then | is printed; a only goes when main ends, so 1 comes last. An object made with new is destroyed only when you delete it: forget the delete and it never prints.Summary
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;