Discussion 8: Review and Practice
One of the activities in discussion today will be practicing drawing full stack-heap diagrams.
Slides
The slides from discussion, as a PDF. If the viewer below doesn't load, use the download link.
Some reminders
- Draw the stack on the left and the heap on the right, at the spot marked
// DRAW HERE(as if the program ran to that point and then paused) - Build the stack from the bottom up, one solid box per function frame, labeled with the function's name. A
{ }block inside a function gets a dashed box on top of its frame. Within a frame, order doesn't matter. - A frame holds every variable its function declares, from the moment it is called. Write
???for any that has no value yet (it should still have a name and type), and(moved)(or x out the pointer/value) for any whose value has moved - Label every variable with its type and any other metadata. A
StringorVechaslenandcapand a slice haslenin addition to pointers. - Draw an arrow from each pointer to the thing it points at. Arrows can go around to the left or the right, whatever's clearer.
Problem 1: types of strings
fn label(word: &str) -> String { let owned = word.to_string(); let count = word.len(); // DRAW HERE println!("{} has {} bytes", owned, count); owned } fn main() { let text = String::from("hello crab"); let piece: &str = &text[6..10]; let lit: &str = "crab"; let out = label(piece); println!("{} | {} | {}", text, out, lit); }
Follow-up questions:
- How many copies of the letters c-r-a-b are in memory when you drew it, and where is each one?
- If
textwere"hello 🦀"instead, what wouldtext.len()be?
Problem 2: on vecs and ints
fn report(score: &i32, history: &Vec<i32>) -> i32 { let best = history[0]; let total = *score + best; // DRAW HERE total } fn main() { let mut score = 40; let bump = &mut score; *bump += 10; let history = vec![70, 65]; let view = &score; let result = report(view, &history); println!("{}", result); }
Follow-up questions:
- How many of
report's arrows end on the heap? - If we didn't use references when passing into
reportand called something likereport(score, history)instead, wouldmainstill compile?