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

Activity 18: Stack and Heap Diagram Practice

Name:

Problems 1 and 2 we do together during lecture. Problem 3 is at the end, and Problem 4 is for if you finish early. Hand this in on your way out.

Instructions

For each code snippet below:

  1. Draw the stack and heap at the moment marked // DRAW HERE
  2. Stack on the left, heap on the right, and build the stack from the bottom up
  3. Label every variable with its type, and give String and Vec their len and cap
  4. Draw an arrow from each pointer to the thing it points at
  5. Box each stack frame separately and label it with the function name
  6. A frame holds every variable its function declares, from the start. Write ??? for any with no value yet, return values included, before you draw the frame above it

Common mistakes

  • Leaving the types off. Half the information in the diagram is in the types
  • Forgetting len and cap on String and Vec
  • Drawing the characters of a String on the stack
  • Drawing a Vec's elements on the stack. An array's go there; a Vec's do not














Problem 1 (in lecture)

Concepts: an array, a Vec, and a String, side by side

fn main() {
    let a = [1, 2, 3];
    let v = vec![1, 2, 3];
    let s = String::from("hi");

    // DRAW HERE
    println!("{:?} {:?} {}", a, v, s);
}































Problem 2 (in lecture)

Concepts: a String on the heap, a string literal in the program, two frames

fn main() {
    let name = String::from("Bob");
    let age = 5;
    print_label("Age", age);
    println!("{}", name);
}

fn print_label(label: &str, value: i32) {
    // DRAW HERE
    println!("{}: {}", label, value);
}













Problem 3

Concepts: a Vec of Vecs, heap pointing at heap

fn main() {
    let grid = vec![vec![1, 2], vec![3, 4], vec![5, 6]];

    // DRAW HERE
    println!("{:?}", grid);
}

































Are 2 and 3 next to each other in memory? Are 1 and 2?




Problem 4: if you finish early

How many bytes does each of these take on the stack? Guess first, then reason it out.

i32 ________ [i32; 3] ________ String ________

Vec<i32> ________ Vec<String> ________ &str ________

Why are String, Vec<i32>, and Vec<String> all the same size?




Solutions

Problem 1

Stack:                                Heap:
┌────────────────────────────┐
│ main                       │
│   a: [i32; 3] = [1, 2, 3]  │
│   v: Vec<i32>              │        ┌───┬───┬───┐
│     ptr ───────────────────┼───────▶│ 1 │ 2 │ 3 │
│     len: 3, cap: 3         │        └───┴───┴───┘
│   s: String                │        ┌─────┬─────┐
│     ptr ───────────────────┼───────▶│ 'h' │ 'i' │
│     len: 2, cap: 2         │        └─────┴─────┘
└────────────────────────────┘

Problem 2

Stack:
┌──────────────────────────┐
│ print_label              │        Program binary:
│   label: &str            │        ┌─────┬─────┬─────┐
│     ptr ─────────────────┼───────▶│ 'A' │ 'g' │ 'e' │
│     len: 3               │        └─────┴─────┴─────┘
│   value: i32 = 5         │
└──────────────────────────┘
┌──────────────────────────┐
│ main                     │        Heap:
│   name: String           │        ┌─────┬─────┬─────┐
│     ptr ─────────────────┼───────▶│ 'B' │ 'o' │ 'b' │
│     len: 3, cap: 3       │        └─────┴─────┴─────┘
│   age: i32 = 5           │
└──────────────────────────┘

Problem 3

Stack:                             Heap:
┌───────────────────────┐          ┌────────────────┐        ┌───┬───┐
│ main                  │      ┌──▶│ ptr ───────────┼───────▶│ 1 │ 2 │
│   grid: Vec<Vec<i32>> │      │   │ len: 2, cap: 2 │        └───┴───┘
│     ptr ──────────────┼──────┘   ├────────────────┤        ┌───┬───┐
│     len: 3, cap: 3    │          │ ptr ───────────┼───────▶│ 3 │ 4 │
└───────────────────────┘          │ len: 2, cap: 2 │        └───┴───┘
                                   ├────────────────┤        ┌───┬───┐
                                   │ ptr ───────────┼───────▶│ 5 │ 6 │
                                   │ len: 2, cap: 2 │        └───┴───┘
                                   └────────────────┘

Are 2 and 3 next to each other? No. They are in different blocks. Are 1 and 2? Yes: they are the two elements of the first inner Vec, side by side in one block.

Problem 4

TypeBytes on the stackWhy
i32432 bits
[i32; 3]12Three i32s, right in the frame
String24ptr, len, cap, 8 bytes each
Vec<i32>24Same three fields
Vec<String>24Same three fields
&str16ptr and len, no cap

String, Vec<i32>, and Vec<String> are all the same size because the stack only ever holds the handle, and the handle is three 8-byte numbers no matter what it points at.