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 27 - Review: everything before Midterm 2

Several blocks funnelling down into one

Announcements




Welcome to Review Day, again

Three weeks of memory, one hour on Friday. Today we'll:

  • Go back over the ideas, in five groups
  • Try a few quick questions on each
  • Sort what you need to know from what was context
  • Spend the last twenty minutes on a confidence quiz and each other's questions

Reminders about the exam

  • Friday, this room, this time, 50 minutes
  • No notes, no devices
  • The practice test has the same five sections and the same point values, and solutions are up today

And for after:

  • Corrections. Discussion in about 2 weeks, like last time, up to half lost points back
  • A strong final counts for more.

What's on it

Everything from the stack lecture through Monday's tests lecture: the stack and the heap, pointers and unsafe, ownership, Vec and Box, strings and slices, the two borrowing rules, and tests.

The code on the paper uses structs, enums, match, and loops, so those still have to be ready, but every question is about this unit.

The sections

SectionPoints
1Quick recall20
2Why does this not compile18
3Safety12
4Stack and heap32
5Hand-coding18

Same shape as the practice test. Look through the whole thing before you start and make a plan.

1. Memory and pointers (Lectures 17 to 19)

Key concepts

  • Memory is a numbered strip of bytes. An address is a number. A pointer is a variable holding an address
  • The stack: one frame per function call, thrown away whole when the function returns. Fast because every size is known ahead of time. A { } inside a function is a mini-frame; a let inside it is a new variable that dies at the end
  • Stack overflow: a function that never stops calling itself fills the stack
  • The heap is for sizes decided while the program runs. A String or Vec is a handle on the stack, ptr, len, cap, with the data on the heap. A &str or &[T] is a pointer and a length, into data that belongs to someone else
  • The CPU reads memory in chunks and keeps them in a cache, so walking along a row of a Vec<Vec<i32>> is faster than walking down a column
  • * means two things. In a type, "pointer to". In an expression, follow it. A reference is a pointer with rules; a raw pointer has none, so following one needs unsafe
  • Three places an arrow can end: the stack (&x), the heap (&v[1]), or the program binary (a literal). The type alone doesn't tell you which

What's not important: real addresses, how the allocator picks a block, or how big the cache is.

Quick questions: memory and pointers

Question 1

Which of these puts data on the heap?

  • A) let a = 5;
  • B) let b = [1, 2, 3];
  • C) let c = String::from("hi");
  • D) let d = "hi";

Answer. C.

Question 2

A String handle carries three numbers. A &str carries two. Which two, and which one is missing?


Answer. A &str has a pointer and a length. It has no capacity, because it doesn't own the letters and can't grow them.

Question 3

#![allow(unused)]
fn main() {
let v = vec![10, 20, 30];
let r = &v[1];
}

Where does r's arrow end on a diagram?

  • A) At v's handle, on the stack
  • B) At the 20, on the heap
  • C) At the 10, on the heap
  • D) In the program binary

Follow-up: and if it werelet r = &v;?

Answer. B. &v[1] is a reference to one element, so the arrow goes straight to the 20 in the heap block. &v would point at the handle instead.

Question 4

Draw the stack and the heap at // DRAW HERE, with a type on every variable.

fn main() {
    let x = 7;
    let v = vec![10, 20, 30];
    let label: &str = "scores";
    let r_x = &x;
    let r_20 = &v[1];
    // DRAW HERE
    println!("{} {} {}", r_x, r_20, label);
}












Answer.

Stack:                               Heap:             Program binary (read-only):
┌──────────────────────────┐
│ 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 ────────────┼─────────────────┘
└──────────────────────────┘

2. Bugs, unsafe, and ownership (Lectures 20 to 22)

Key concepts

  • The seven bugs: leak, use-after-free, double free, dangling pointer, buffer overflow, null pointer, data race. Be able to go back and forth between the name and a short description
  • unsafe means taking responsibility. The compiler can't check a raw pointer, so you promise it's valid. malloc gives bytes with garbage in them; you write before you read, and you free exactly once
  • Three ownership rules: every value has an owner, only one at a time, and it is dropped when the owner goes out of scope. Rule 3 is free done for you, always once
  • Move or copy. Numbers, bool, char, and &T copy. Anything that owns heap data moves: the handle changes hands and the heap doesn't change. Your own struct moves unless you #[derive(Clone, Copy)]
  • .clone() makes a second heap block.
  • Passing to a function follows the same rules. Returning hands ownership back out
  • Vec growth: when len reaches cap and you push, it asks for a bigger block, copies the elements, writes the new one, and frees the old block
  • Box::new(x) puts x on the heap with a pointer on the stack that owns it

What's not important: reading C, writing unsafe yourself

Quick questions: bugs and ownership

Question 5

For each mistake, what does safe Rust do about it: compile error, panic when it runs, or prevented automatically (there is no way to write it)?

  • a) Use a String after moving it into a function
  • b) Forget to free a Vec


Answer. a) Compile error. The compiler knows the value moved. b) Prevented automatically. The owner drops it at the end.

Question 6

Does this compile? If not, which line, and which rule?

#![allow(unused)]
fn main() {
let s1 = String::from("hello");
let s2 = s1;
let s3 = s1.clone();
println!("{}", s2);
}

Answer. No. Line 3: s1 moved into s2 on line 2, so there is nothing left to clone. Rule 2, one owner at a time.

Question 7

v1 is a Vec<i32> holding three numbers. After let v2 = v1;, how many copies of the three numbers are on the heap? And after let v2 = v1.clone(); instead?

  • A) 0 and 1
  • B) 1 and 1
  • C) 1 and 2
  • D) 2 and 2

Answer. C.

3. Strings and slices (Lecture 23)

Key concepts

  • Three types of string. String owns letters on the heap. &String points at the handle. &str points at letters, on the heap or in the binary. Write &str in signatures: it accepts a &String, a literal, or a slice
  • .len() is bytes. .chars().count() is characters. Plain ASCII letters are 1 byte each, accented letters like é or ñ are 2, Chinese, Japanese, and Korean characters are 3, and emoji are 4. Slicing is by byte, so &s[0..2] can land inside a character and panic, and s[0] doesn't compile at all
  • A slice is a view: a pointer and a length into data that belongs to someone else, so it has no capacity. &s[1..3] on a String and &v[1..3] on a Vec or an array are the same idea
  • .chars() walks the characters, .collect() builds a String back out of them

What's not important: the actual bit patterns of UTF-8, or anything about format! beyond {} and {:?}.

Quick questions: strings and slices

Question 8

Explain in one sentence why this panics.

#![allow(unused)]
fn main() {
let text = "🦀Hello";
let slice = &text[0..2];
}

Answer. The crab is four bytes, so byte 2 is in the middle of it, and Rust refuses to hand out half a character. The message says byte index 2 is not a char boundary.

Question 9

What does this print?

#![allow(unused)]
fn main() {
let v = vec![10, 20, 30, 40, 50];
let a = &v[1..4];
let b = &a[1..];
println!("{} {} {:?}", a[0], b[0], b);
}

Answer. 20 30 [30, 40]. A slice counts from its own start, so a[0] is the 20 at v's index 1, and a is [20, 30, 40]. b is a slice of that slice, from a's index 1 on, so it is [30, 40] and b[0] is the 30. All three point into the same five numbers on the heap: a.ptr at the 20 with len 3, b.ptr at the 30 with len 2.

4. Borrowing (Lectures 24 and 25)

Key concepts

  • Rule 1: any number of &, or exactly one &mut, never both at once. The owner's own name counts as a writer
  • Rule 2: a reference never outlives what it points at
  • A borrow lasts until its last use, which is usually before the closing brace. The error marks three places: the reader, the writer, and the later use that kept the reader alive
  • A &mut into part of a vector is a &mut to the whole vector, because push can move everything
  • Three things a function can ask for. &T to look. &mut T to change the caller's data. T to keep it. .clone() at the call site when you need two copies that will diverge, and know what it costs
  • In let mut r = &mut y; the first mut lets r be re-pointed, the second lets y change through it with *r
  • Lifetimes, read only. <'a> on a function means it returns a borrow of one of its inputs. 'static means the data is there for the whole program, which is why literals live in the binary

What's not important: deciding whether a lifetime annotation is needed, writing one, or exactly when auto-deref happens.

Quick questions: borrowing

Question 10

Fill in the two blanks so this compiles and prints [90, 95, 83].

fn update_scores(scores: _____, bonus: i32) {
    for score in scores.iter_mut() {
        *score += bonus;
    }
}

fn main() {
    let mut data = vec![85, 90, 78];
    update_scores(_____, 5);
    println!("{:?}", data);
}

Answer. &mut Vec<i32> and &mut data.

Question 11

Where is the borrow checker error here, and why?

#![allow(unused)]
fn main() {
let mut x = vec![1, 2, 3];
let r1 = &x;
x.push(4);
println!("{:?}", r1);
}

Answer. The push on line 3 is a writer, and r1 is a reader that is still alive because it is used on line 4. Rule 1, one writer or many readers.

5. Tests (Lecture 26)

Key concepts

  • A test is a function with #[test] above it, no parameters, no return. It fails by panicking, and assert!, assert_eq!, assert_ne!, and #[should_panic] are how you panic on purpose
  • Any assert takes a message after its values. You only see it when the test fails, which is exactly when you want it
  • One thing per test. The happy path is worth a test. The edges are worth more: empty, one, zero, exactly on the boundary
  • A test can be wrong too. Reading a test means reading the code and the expectation
  • Write one from a signature and a sentence. The description usually hands you the ordinary case and one edge for free

What's not important: setting up a tests module from memory, or cargo test flags.

Quick question: tests

Question 12

A classmate's test:

fn empty_input() {
    assert_eq!(count_long(&[], 4), 0);
}

Two things are missing before this does its job. What are they?


Answer. The #[test] line above it, without which cargo test never runs it, and a message after the values, so a failure says what was expected in words: "no words means nothing is long". The test itself is a good edge case.

Tips by exam section

Recall. One line or one word per blank. If one stumps you, write your best guess and move on.

Why does this not compile. Read the compiler's message for what it expected and what it found. The fix is often a line above the one it points at, and sometimes two lines, a signature and its call. For the borrowing ones, bracket each borrow from where it is made to its last use before you decide which rule.

Safety. Read the unsafe program in order, and think about what has to be going on in memory for it to work. For an edit, it can help to draw out for yourself what's happening in memory to figure out what the bug is.

Stack and heap. Don't forget types! Write every variable with its type before drawing an arrow, including the ones the function hasn't used yet. ptr, len, cap on a handle; ptr and len on a slice. Frames bottom-up, a dashed box for a { }, ??? for no value yet. Arrows need to be precise.

Hand-coding. Signature first, then the skeleton, then the details. The other code snippets on the exam can be references for good syntax, so use them.

Activity 27: Confidence check + passing sheets

See Activity 27.

Like last time - it's not a quiz. Read each line, mark Got it, Shaky, or Study it, and keep the sheet for studying.

Submit photos on gradescope when you're done.

At the same time

I'll pass out a few sheets, some marked "Q&A" and some marked "Tips and Encouragement"

  • The Q&A sheet is divided up with sections where you can write a question for others to answer, about content or studying or anything else. When you get the sheet, you can answer in the same box
  • The tips and encouragement sheet is open to writing anything anywhere

I'll scan them all and post them after