Arguments and Borrowing

We’ve got some basic examples with the stack and the heap going, but what about function arguments and borrowing? Here’s a small Rust program:

fn foo(i: &i32) {
    let z = 42;
}

fn main() {
    let x = 5;
    let y = &x;

    foo(y);
}

When we enter main(), memory looks like this:

AddressNameValue
1y→ 0
0x5

x is a plain old 5, and y is a reference to x. So its value is the memory location that x lives at, which in this case is 0.

What about when we call foo(), passing y as an argument?

AddressNameValue
3z42
2i→ 0
1y→ 0
0x5

Stack frames aren’t only for local bindings, they’re for arguments too. So in this case, we need to have both i, our argument, and z, our local variable binding. i is a copy of the argument, y. Since y’s value is 0, so is i’s.

This is one reason why borrowing a variable doesn’t deallocate any memory: the value of a reference is a pointer to a memory location. If we got rid of the underlying memory, things wouldn’t work very well.

A complex example

fn foo(x: &i32) {
    let y = 10;
    let z = &y;

    baz(z);
    bar(x, z);
}

fn bar(a: &i32, b: &i32) {
    let c = 5;
    let d = Box::new(5);
    let e = &d;

    baz(e);
}

fn baz(f: &i32) {
    let g = 100;
}

fn main() {
    let h = 3;
    let i = Box::new(20);
    let j = &h;

    foo(j);
}

First, we call main():

AddressNameValue
(2 ** 30) - 120
.........
2j→ 0
1i→ (2 ** 30) - 1
0h3

We allocate memory for j, i, and h. i is on the heap, and so has a value pointing there.

Next, at the end of main(), foo() gets called:

AddressNameValue
(2 ** 30) - 120
.........
5z→ 4
4y10
3x→ 0
2j→ 0
1i→ (2 ** 30) - 1
0h3

Space gets allocated for x, y, and z. The argument x has the same value as j, since that’s what we passed it in. It’s a pointer to the 0 address, since j points at h.

Next, foo() calls baz(), passing z:

AddressNameValue
(2 ** 30) - 120
.........
7g100
6f→ 4
5z→ 4
4y10
3x→ 0
2j→ 0
1i→ (2 ** 30) - 1
0h3

We’ve allocated memory for f and g. baz() is very short, so when it’s over, we get rid of its stack frame:

AddressNameValue
(2 ** 30) - 120
.........
5z→ 4
4y10
3x→ 0
2j→ 0
1i→ (2 ** 30) - 1
0h3

Next, foo() calls bar() with x and z:

AddressNameValue
(2 ** 30) - 120
(2 ** 30) - 25
.........
10e→ 9
9d→ (2** 30) - 2
8c5
7b→ 4
6a→ 0
5z→ 4
4y10
3x→ 0
2j→ 0
1i→ (2 ** 30) - 1
0h3

We end up allocating another value on the heap, and so we have to subtract one from (230) - 1. It’s easier to write that than 1,073,741,822. In any case, we set up the variables as usual.

At the end of bar(), it calls baz():

AddressNameValue
(2 ** 30) - 120
(2 ** 30) - 25
.........
12g100
11f→ (2 ** 30) - 2
10e→ 9
9d→ (2** 30) - 2
8c5
7b→ 4
6a→ 0
5z→ 4
4y10
3x→ 0
2j→ 0
1i→ (2 ** 30) - 1
0h3

With this, we’re at our deepest point! Whew! Congrats for following along this far.

After baz() is over, we get rid of f and g:

AddressNameValue
(2 ** 30) - 120
(2 ** 30) - 25
.........
10e→ 9
9d→ (2** 30) - 2
8c5
7b→ 4
6a→ 0
5z→ 4
4y10
3x→ 0
2j→ 0
1i→ (2 ** 30) - 1
0h3

Next, we return from bar(). d in this case is a Box, so it also frees what it points to: (2 ** 30) - 2.

AddressNameValue
(2 ** 30) - 120
.........
5z→ 4
4y10
3x→ 0
2j→ 0
1i→ (2 ** 30) - 1
0h3

And after that, foo() returns:

AddressNameValue
(2 ** 30) - 120
.........
2j→ 0
1i→ (2 ** 30) - 1
0h3

What do other languages do?

Most languages with a garbage collector heap-allocate by default. This means that every value is boxed. There are a number of reasons why this is done, but they’re out of scope for this tutorial. There are some possible optimizations that don’t make it true 100% of the time, too. Rather than relying on the stack and Drop to clean up memory, the garbage collector deals with the heap instead.

Which to use?

So if the stack is faster and easier to manage, why do we need the heap? A big reason is that Stack-allocation alone means you only have 'Last In First Out (LIFO)' semantics for reclaiming storage. Heap-allocation is strictly more general, allowing storage to be taken from and returned to the pool in arbitrary order, but at a complexity cost.

Generally, you should prefer stack allocation, and so, Rust stack-allocates by default. The LIFO model of the stack is simpler, at a fundamental level. This has two big impacts: runtime efficiency and semantic impact.

Runtime Efficiency

Managing the memory for the stack is trivial: The machine increments or decrements a single value, the so-called “stack pointer”. Managing memory for the heap is non-trivial: heap-allocated memory is freed at arbitrary points, and each block of heap-allocated memory can be of arbitrary size, so the memory manager must generally work much harder to identify memory for reuse.

If you’d like to dive into this topic in greater detail, this paper is a great introduction.

Semantic impact

Stack-allocation impacts the Rust language itself, and thus the developer’s mental model. The LIFO semantics is what drives how the Rust language handles automatic memory management. Even the deallocation of a uniquely-owned heap-allocated box can be driven by the stack-based LIFO semantics, as discussed throughout this chapter. The flexibility (i.e. expressiveness) of non LIFO-semantics means that in general the compiler cannot automatically infer at compile-time where memory should be freed; it has to rely on dynamic protocols, potentially from outside the language itself, to drive deallocation (reference counting, as used by Rc<T> and Arc<T>, is one example of this).

When taken to the extreme, the increased expressive power of heap allocation comes at the cost of either significant runtime support (e.g. in the form of a garbage collector) or significant programmer effort (in the form of explicit memory management calls that require verification not provided by the Rust compiler).