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

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.

Download the slides (PDF)

Some reminders

  1. 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)
  2. 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.
  3. 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
  4. Label every variable with its type and any other metadata. A String or Vec has len and cap and a slice has len in addition to pointers.
  5. 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:

  1. How many copies of the letters c-r-a-b are in memory when you drew it, and where is each one?
  2. If text were "hello 🦀" instead, what would text.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:

  1. How many of report's arrows end on the heap?
  2. If we didn't use references when passing into report and called something like report(score, history) instead, would main still compile?