Activity 19: Draw the Arrows, Then Poke at Them
Name:
Part 1 we do together during lecture. Part 2 is at the end, with a laptop. Hand this in on your way out.
Part 1: Draw the arrows
Stack on the left, heap on the right. Types on everything and arrows from references to what they point to.
Problem 1 (in lecture)
fn main() { let mut x = 10; let y = 20; let r1 = &y; let r2 = &mut x; *r2 = 15; // DRAW HERE }
Problem 2 (in lecture)
fn main() { let numbers = vec![10, 20, 30, 40]; let name = String::from("Alice"); let r1 = &numbers; let r2 = &numbers[1]; let r3 = &name; let r4: &str = "Bob"; // DRAW HERE }
Part 2: Poke at pointers
The code for each experiment is on the website version of this page: you can even press the Run button at the top right of the block, and edit it right there. Or copy it into Rust Playground.
Run it, write down what you see, then make the change and run it again. Addresses will be different from your neighbors'. The interesting part is which ones match and which ones are close.
Experiment 1: an arrow into another frame
fn with_bonus(points: &i32) -> i32 { println!("points holds {:p}", points); println!("points lives at {:p}", &points); let result = *points + 5; result } fn main() { let score = 10; println!("score lives at {:p}", &score); let total = with_bonus(&score); println!("score {score}, total {total}"); }
a. Which two addresses match? Why?
b. points lives somewhere too. Is its address close to score's, or far away? Where is it?
c. Change it: add the line *points += 5; inside with_bonus, to change score directly. What does the compiler complain about, in your own words?
Experiment 2: watch a Vec move
fn main() { let mut v: Vec<i32> = Vec::new(); for i in 0..20 { v.push(i); println!("len {:2} cap {:2} data at {:p}", v.len(), v.capacity(), v.as_ptr()); } }
a. When does cap change? What is the pattern?
b. When does the data at address change? Why would the data move at all?
c. Change it: replace Vec::new() with Vec::with_capacity(20). What is different?
Experiment 3: break it on purpose
fn main() { let r: &i32; { let x = 5; r = &x; } println!("{r}"); }
a. This does not compile. Copy the first line of the error.
b. In your own words, what is the compiler worried about?
c. Change it: move the println! up, inside the braces. What happens?
Experiment 4, if you finish early: how big is an arrow?
Fill in your guesses before you run it.
fn main() { println!("i32 {} bytes", size_of::<i32>()); println!("&i32 {} bytes", size_of::<&i32>()); println!("String {} bytes", size_of::<String>()); println!("&String {} bytes", size_of::<&String>()); println!("&str {} bytes", size_of::<&str>()); println!("[i32; 1000] {} bytes", size_of::<[i32; 1000]>()); println!("&[i32; 1000] {} bytes", size_of::<&[i32; 1000]>()); }
| Type | Guess | Actual |
|---|---|---|
i32 | ||
&i32 | ||
String | ||
&String | ||
&str | ||
[i32; 1000] | ||
&[i32; 1000] |
a. Why is &[i32; 1000] so much smaller than [i32; 1000]?
b. Which reference is not 8 bytes, and why?
c. Change it: add a line for a type of your choice. bool? char? Vec<String>? &&i32? What did you try, and what did you get?
Experiment 5, if you finish early: an arrow to an arrow
fn main() { let x: i32 = 5; let r: &i32 = &x; let rr: &&i32 = &r; println!("x lives at {:p}", &x); println!("r holds {:p}", r); println!("r lives at {:p}", &r); println!("rr holds {:p}", rr); println!("{} {} {}", x, *r, **rr); }
a. Which addresses match? Draw x, r, and rr on the stack with their arrows.
b. Why does rr need two stars to get to the 5?
Solutions
Part 1
Problem 1.
Stack:
┌────────────────────┐
│ main() │
│ ├ x: i32 = 15 │◀──┐
│ ├ y: i32 = 20 │◀┐ │
│ ├ r1: &i32 ────────┼─┘ │
│ └ r2: &mut i32 ────┼───┘
└────────────────────┘
Stack only, nothing on the heap. x is 15, not 10: *r2 = 15 followed the arrow and wrote into x. r1 points at y and r2 at x, so both arrows end in the same frame they start in.
Problem 2.
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" │
└──────────────────────────┘ └───────┘
Four arrows, ending in three different places. r1 and r3 end on the stack, at the handles: &numbers is a reference to the variable numbers, and that variable is the handle, not the numbers. r2 ends in the heap, at the 20, because &numbers[1] is a reference to one element. r4 is a &str, so it carries a len of its own and points into the program binary, where the literal "Bob" has been since compile time.
Part 2
Your addresses will differ from these. Which ones match, and which are close, should be the same on every machine.
Experiment 1.
score lives at 0x16f1ce6f4
points holds 0x16f1ce6f4
points lives at 0x16f1ce678
score 10, total 15
- a.
score lives atandpoints holdsmatch.pointsis&score, so what it holds isscore's address - b.
points lives atis close toscore, a few hundred bytes away at most, but not the same.pointsis a variable too, with its own spot on the stack, inwith_bonus's frame, which sits right on top ofmain's - c.
*points += 5;does not compile: "cannot assign to*points, which is behind a&reference". A&reference lets you read through the arrow but not write through it.
Experiment 2.
len 1 cap 4 data at 0x104955390
len 2 cap 4 data at 0x104955390
len 3 cap 4 data at 0x104955390
len 4 cap 4 data at 0x104955390
len 5 cap 8 data at 0x104955200
...
len 8 cap 8 data at 0x104955200
len 9 cap 16 data at 0x104955220
...
len 16 cap 16 data at 0x104955220
len 17 cap 32 data at 0x104955ea0
...
len 20 cap 32 data at 0x104955ea0
- a.
capchanges whenlencatches up to it: 4, 8, 16, 32. It doubles every time it fills - b. The address changes at the same moments. A bigger block means a new allocation somewhere else, and every element is copied over to it, then the old block is freed. (Now and then the allocator can grow a block in place, so the address may stay put once or twice)
- c. With
Vec::with_capacity(20),capis 20 from the first line and the address never changes. No regrowing and no copying, because the room was there from the start
Experiment 3.
- a.
error[E0597]: `x` does not live long enough - b.
xlives inside the braces and is dropped at the closing one.rwould still be pointing at wherexused to be, andprintln!would read it. The compiler refuses to make a dangling pointer, and the full message says wherexis dropped and where the borrow is used afterward - c. Moving the
println!inside the braces compiles and prints5. Nowris used whilexis still alive
Experiment 4.
| Type | Actual |
|---|---|
i32 | 4 |
&i32 | 8 |
String | 24 |
&String | 8 |
&str | 16 |
[i32; 1000] | 4000 |
&[i32; 1000] | 8 |
- a. A reference is an address, and an address is 8 bytes on a 64-bit machine no matter how big the thing it points at is.
&[i32; 1000]holds where to find the 4000 bytes, not the bytes - b.
&str, at 16. It is a fat pointer: an address plus a length, because the text it points at could be any length and nothing else records it.&Stringis 8, because theStringhandle carries its ownlen - c. Some to compare against:
boolis 1,charis 4,Vec<String>is 24,&&i32is 8. Every plain reference is 8
Experiment 5.
x lives at 0x16dd16634
r holds 0x16dd16634
r lives at 0x16dd16638
rr holds 0x16dd16638
5 5 5
- a.
x lives atmatchesr holds, andr lives atmatchesrr holds.r lives atis 4 bytes pastxhere:ris a variable on the stack too, right next tox
Stack:
┌──────────────────────┐
│ main() │
│ ├ x: i32 = 5 │◀───┐
│ ├ r: &i32 ───────────┼────┘
│ │ ▲ │
│ └ rr: &&i32 │
└──────────────────────┘
- b. Each
*follows one arrow.rrpoints atr, so*rrisr, which is itself an arrow. One more*follows that arrow to the 5