Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 19 - Pointers: &, * , and unsafe

A box holding an arrow that points at another box

Announcements




A shortcut to a 4 GB video

You make a desktop shortcut (an "alias" on a Mac) to a 4 GB video. The shortcut itself is a few kilobytes.

Where is the video?

Where it was originally. The shortcut just gives directions for where to find the video, and if you delete the video the directions are still there, just invalid.

A value that holds where to find something is a called pointer.

Where we left off

Tuesday we printed addresses: &x asks for the address of x, and {:p} prints it. The p was for pointer.

Wednesday we drew a lot of arrows like this:

Stack:                    Heap:
┌─────────────┐          ┌─────┬─────┬─────┬─────┬─────┐
│ s1: String  │          │ 'h' │ 'e' │ 'l' │ 'l' │ 'o' │
│ ├ ptr ──────┼─────────▶│     │     │     │     │     │
│ ├ len: 5    │          └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 5    │
└─────────────┘

Every arrow we drew was a pointer: a value that holds an address.

Learning objectives

By the end of class today you should be able to:

  • Explain how a pointer, a reference, and a String's ptr field are the same idea
  • Read the type *const i32 out loud and say what it holds
  • Explain what dereferencing does, and why Rust makes you write unsafe to do it
  • Draw a reference in a stack and heap diagram, and say where its arrow ends

That arrow, printed

fn main() {
    let x: i32 = 7;
    let s = String::from("hello");

    println!("address of x            {:p}", &x);
    println!("address of s (handle)   {:p}", &s);
    println!("s's ptr (text)          {:p}", s.as_ptr());
    println!("s's len                 {}", s.len());
    println!("s's cap                 {}", s.capacity());
}

s.as_ptr(), s.len(), and s.capacity() hand you the three fields from Wednesday's diagram. ptr is the address at the tip of the arrow.

What do you notice?

x and s are neighbors on the stack. The text is somewhere else entirely. The arrow from the stack to the heap is just that second number.

A pointer is a variable that holds an address

fn main() {
    let x1: i32 = 10;
    // Turns a reference into a raw pointer. You will read this, not write it
    let ptr_x1: *const i32 = &x1 as *const i32;

    println!("address of x1 {:p}", &x1);
    println!("size of x1 {}", size_of::<i32>());
    println!("ptr_x1 points to {:p}", ptr_x1);
    println!("size of ptr_x1 {}", size_of::<*const i32>());
}

So ptr_x1 does not contain an i32, it contains an address to an i32.

Two things to notice in the output:

  • The address inside ptr_x1 is the address of x1
  • ptr_x1 is 8 bytes, the size of an address on this machine. An i32 is 4

Both variables are fixed size, so both live on the stack. x1 is 4 bytes holding 10. ptr_x1 is 8 bytes holding an address, the same size as the ptr field in a String.

Stack:
┌──────────────────────────────┐
│ main()                       │
│ ├ x1: i32 = 10               │◀─┐
│ └ ptr_x1: *const i32 ────────┼──┘
└──────────────────────────────┘

New today: pointers can go from the stack back to the stack too!

Dereferencing: follow the address

fn main() {
    let x1: i32 = 10;
    let ptr_x1: *const i32 = &x1 as *const i32;
    unsafe {
        println!("{}", *ptr_x1);
    }
}

*ptr_x1 means follow the address in ptr_x1 and look at what is there.

Why did that need unsafe?

Dereferencing (raw pointers) is dangerous!

Nothing guarantees that the address:

  • is a valid address at all
  • holds a value of the type you think
  • has been initialized
  • has not been changed or freed by some other part of the program

So Rust makes you swear you know what you're doing. It's like signing a waiver before you jump out of an airplane - it says you are taking responsibility for this one.

A pointer is not a copy

fn main() {
    let mut x1: i32 = 10;
    let ptr_x1: *const i32 = &x1 as *const i32;
    x1 = 30;
    unsafe {
        println!("{}", *ptr_x1);
    }
}

What does this print?

30. The pointer holds an address. Change what is at the address and what the pointer sees changes.

You can write through a pointer too

fn main() {
    let mut x1: i32 = 10;
    // Same conversion, for a pointer you can write through
    let ptr_x1: *mut i32 = &mut x1 as *mut i32;
    unsafe {
        *ptr_x1 = 50;
    }
    println!("{x1}");
}

*mut i32 instead of *const i32. Now dereferencing gives you something you can assign to.

There's is a lot of new syntax today! While you'll need to write unsafe rust in the project, and will read some on the exam, you won't need to hand-code it or remember the syntax details perfectly. Everyday Rust uses & and *, and soon our focus will just be on using those well.

References: a pointer with rules

Typically, we don't really writte let ptr_x1: *mut i32 = &mut x1 as *mut i32;... we just make a "reference":

fn main() {
    let x1: i32 = 10;
    let ref_x1: &i32 = &x1;

    println!("address of x1     {:p}", &x1);
    println!("ref_x1 refers to  {:p}", ref_x1);
    println!("ref_x1's value is {}", ref_x1);
}

A reference is a pointer. Same 8 bytes, same address inside.

Two differences from "bare" pointers:

  1. We didn't need unsafe. I wonder why...
  2. No * to read it. Dereferencing can sometimes be inferred in Rust, like types.

Read-only and read-write references

References come in two flavors:

  • &T, an immutable reference: read-only (like &self)
  • &mut T, a mutable reference: read and write (like &mut self)
fn main() {
    let mut x1: i32 = 10;
    let r: &mut i32 = &mut x1;
    *r += 1;
    println!("x1 is now {}", x1);
}

So the type of r here is &mut i32 (if it were an immutable ref its type would be &i32)

That *r is the same dereference operator from before, but this time we can trust it (we don't need unsafe!).

Activity 19, Problem 1: draw the arrows

See Problem 1 on Activity 19.

Stack:
┌────────────────────┐
│ main()             │
│ ├ x: i32 = 15      │◀──┐
│ ├ y: i32 = 20      │◀┐ │
│ ├ r1: &i32 ────────┼─┘ │
│ └ r2: &mut i32 ────┼───┘
└────────────────────┘

x is 15, not 10: *r2 = 15 followed the arrow and wrote into x. Both arrows end in the stack, and nothing is on the heap.

Within a frame you can write bottom-up or top-down, it doesn't matter.

Where can an arrow point?

fn main() {
    let x: i32 = 7;
    let v = vec![10, 20, 30];
    let label: &str = "scores";

    let r_x: &i32 = &x;
    let r_20: &i32 = &v[1];

    println!("r_x points to    {:p}", r_x);
    println!("r_20 points to   {:p}", r_20);
    println!("label points to  {:p}", label);
}

Which one points into the stack?

r_x. Its address is nowhere near the other two. r_20 points into the heap, and label points into the program itself.

Look at what printed for label: metadata: 6. That's the length. A &str is a pointer plus a length, called a fat pointer. More on those in the strings lecture.

Three places an arrow can end

Stack:                               Heap:             Program:
┌──────────────────────────┐
│ main()                   │
│ ├ x: i32 = 7             │◀─┐
│ ├ v: Vec<i32>            │  │       ┌────┬────┬────┐
│ │  ├ ptr ────────────────┼──┼──────▶│ 10 │ 20 │ 30 │
│ │  ├ len: 3              │  │       └────┴────┴────┘
│ │  └ cap: 3              │  │              ▲
│ ├ label: &str            │  │              │         ┌──────────┐
│ │  ├ ptr ────────────────┼──┼──────────────┼────────▶│ "scores" │
│ │  └ len: 6              │  │              │         └──────────┘
│ ├ r_x: &i32 ─────────────┼──┘              │
│ └ r_20: &i32 ────────────┼─────────────────┘
└──────────────────────────┘
  • Into the stack: &x
  • Into the heap: &v[1] points straight at the 20, not at v
  • Into the program: a string literal

r_x and r_20 are both &i32. The type does not tell you where the arrow ends.

The handle, or the element?

Same v as before. &v[1] pointed at the 20. What does &v point at?

fn main() {
    let v = vec![10, 20, 30];
    let whole: &Vec<i32> = &v;
    let first: &i32 = &v[0];

    println!("address of v     {:p}", &v);
    println!("v's ptr          {:p}", v.as_ptr());
    println!("v's len          {}", v.len());
    println!("whole points to  {:p}", whole);
    println!("first points to  {:p}", first);
}

Which addresses match?

whole matches the address of v: it points at the handle, on the stack. first matches v's ptr field: it points at the first element, on the heap.

&v points at the handle

Stack:                                   Heap:
     ┌──────────────────────────┐
     │ main()                   │
  ┌─▶│ ├ v: Vec<i32>            │        ┌────┬────┬────┐
  │  │ │  ├ ptr ────────────────┼───────▶│ 10 │ 20 │ 30 │
  │  │ │  ├ len: 3              │        └────┴────┴────┘
  │  │ │  └ cap: 3              │          ▲
  └──┼── whole: &Vec<i32>       │          │
     │ └ first: &i32 ───────────┼──────────┘
     └──────────────────────────┘
  • whole: &Vec<i32> is an arrow to the handle: v itself, three fields on the stack
  • first: &i32 is an arrow to the first element, the same address v's own ptr holds

This is the arrow everyone draws wrong. Asked to draw &v, most people run the arrow straight to the numbers. A reference points at the thing you put the & in front of, and here that is v, the handle.

Activity 19, Problem 2: four arrows

See Problem 2 on Activity 19.

Stack:                                  Heap:
┌──────────────────────────┐
│ main()                   │
│ ├ numbers: Vec<i32>      │◀──┐        ┌────┬────┬────┬────┐
│ │  ├ ptr ────────────────┼───┼───────▶│ 10 │ 20 │ 30 │ 40 │
│ │  ├ len: 4              │   │        └────┴────┴────┴────┘
│ │  └ cap: 4              │   │               ▲
│ ├ name: String           │◀┐ │               │    ┌─────┬─────┬─────┬─────┬─────┐
│ │  ├ ptr ────────────────┼─┼─┼───────────────┼───▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ │  ├ len: 5              │ │ │               │    └─────┴─────┴─────┴─────┴─────┘
│ │  └ cap: 5              │ │ │               │
│ ├ r1: &Vec<i32> ─────────┼─┼─┘               │
│ ├ r2: &i32 ──────────────┼─┼─────────────────┘
│ ├ r3: &String ───────────┼─┘
│ └ r4: &str               │            Program binary:
│    ├ ptr ────────────────┼───────────▶┌───────┐
│    └ len: 3              │            │ "Bob" │
└──────────────────────────┘            └───────┘

Two of the four arrows end on the stack: r1 and r3, at the handles. r2 goes into the heap, at the 20, and r4 into the program.

An arrow into another frame

fn with_bonus(points: &i32) -> i32 {
    let result = *points + 5;
    result
}

fn main() {
    let score = 10;
    let total = with_bonus(&score);
    println!("{score} {total}");
}

What does this print?

10 15. with_bonus never sees score by name. It gets an arrow to it, follows the arrow to read the 10, and leaves score alone.

Drawn with Tuesday's frames

Stack:
┌──────────────────────────┐
│ with_bonus()             │
│ ├ points: &i32 ──────────┼──┐
│ └ result: i32 = 15       │  │
├──────────────────────────┤  │
│ main()                   │  │
│ ├ score: i32 = 10        │◀─┘
│ └ total: i32 = ???       │
└──────────────────────────┘

points lives in with_bonus's frame and points down, into main's. *points follows the arrow and reads score where it lives. The only thing copied was 8 bytes of address.

When with_bonus returns, its frame is thrown away, arrow and all. The 15 in result is copied out into total first, the same as Tuesday's add_one. score stays behind, untouched.

Every &self method you have written works this way.

What if the arrow points the other way?

fn make_number() -> &i32 {
    let x = 42;
    &x
}

fn main() {
    let r = make_number();
    println!("{}", r);
}
Stack:
░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░ make_number()  (gone)    ░
░ └ x: i32 = 42            ░◀─┐
░░░░░░░░░░░░░░░░░░░░░░░░░░░░  │
┌──────────────────────────┐  │
│ main()                   │  │
│ └ r: &i32 ───────────────┼──┘
└──────────────────────────┘

make_number returns, and its frame is thrown away. The arrow is still there, pointing at memory that is no longer anybody's.

It is the shortcut to a deleted video. Rust refuses to compile this. C compiles it, with a warning at most.

Activity 19, Part 2: poke at pointers

Laptops out, one per pair. Open Activity 19 on the course website.

Run each experiment, change what it tells you to change, and write what you see on your sheet to turn in. (Just get as far as you can.)