The Stack and the Heap
As a systems language, Rust operates at a low level. If you’re coming from a high-level language, there are some aspects of systems programming that you may not be familiar with. The most important one is how memory works, with a stack and a heap. If you’re familiar with how C-like languages use stack allocation, this chapter will be a refresher. If you’re not, you’ll learn about this more general concept, but with a Rust-y focus.
As with most things, when learning about them, we’ll use a simplified model to start. This lets you get a handle on the basics, without getting bogged down with details which are, for now, irrelevant. The examples we’ll use aren’t 100% accurate, but are representative for the level we’re trying to learn at right now. Once you have the basics down, learning more about how allocators are implemented, virtual memory, and other advanced topics will reveal the leaks in this particular abstraction.
Memory management
These two terms are about memory management. The stack and the heap are abstractions that help you determine when to allocate and deallocate memory.
Here’s a high-level comparison:
- The stack is very fast, and is where memory is allocated in Rust by default. But the allocation is local to a function call, and is limited in size.
- The heap, on the other hand, is slower, and is explicitly allocated by your program. But it’s effectively unlimited in size, and is globally accessible. Note this meaning of heap, which allocates arbitrary-sized blocks of memory in arbitrary order, is quite different from the heap data structure.
The Stack
Let’s talk about this Rust program:
fn main() { let x = 42; }
This program has one variable binding, x. This memory needs to be allocated from somewhere. Rust ‘stack allocates’ by default, which means that basic values ‘go on the stack’. What does that mean?
Well, when a function gets called, some memory gets allocated for all of its local variables and some other information. This is called a stack frame, and for the purpose of this tutorial, we’re going to ignore the extra information and only consider the local variables we’re allocating. So in this case, when main() is run, we’ll allocate a single 32-bit integer for our stack frame. This is automatically handled for you, as you can see; we didn’t have to write any special Rust code or anything.
When the function exits, its stack frame gets deallocated. This happens automatically as well.
That’s all there is for this simple program. The key thing to understand here is that stack allocation is very, very fast. Since we know all the local variables we have ahead of time, we can grab the memory all at once. And since we’ll throw them all away at the same time as well, we can get rid of it very fast too.
The downside is that we can’t keep values around if we need them for longer than a single function. We also haven’t talked about what the word, ‘stack’, means. To do that, we need a slightly more complicated example:
fn foo() { let y = 5; let z = 100; } fn main() { let x = 42; foo(); }
This program has three variables total: two in foo(), one in main(). Just as before, when main() is called, a single integer is allocated for its stack frame. But before we can show what happens when foo() is called, we need to visualize what’s going on with memory. Your operating system presents a view of memory to your program that’s pretty simple: a huge list of addresses, from 0 to a large number, representing how much RAM your computer has. For example, if you have a gigabyte of RAM, your addresses go from 0 to 1,073,741,823. That number comes from (2 ** 30), the number of bytes in a gigabyte.
‘Gigabyte’ can mean two things: (10 ** 09, 1,000,000,000), or (2 ** 30, 102410241024 = 1,073,741,824). The IEC standard resolved this by stating that ‘gigabyte’ is (10 ** 9), and ‘gibibyte’ is ( 2 ** 30). However, very few people use this terminology, and rely on context to differentiate. We follow in that tradition here.
This memory is kind of like a giant array: addresses start at zero and go up to the final number. So here’s a diagram of our first stack frame:
| Address | Name | Value |
|---|---|---|
| 0 | x | 42 |
We’ve got x located at address 0, with the value 42.
When foo() is called, a new stack frame is allocated:
| Address | Name | Value |
|---|---|---|
| 2 | z | 100 |
| 1 | y | 5 |
| 0 | x | 42 |
Because 0 was taken by the first frame, 1 and 2 are used for foo()’s stack frame. It grows upward, the more functions we call. Notice that we are not taking into account the size of each variable (for example, a 32 bit variable would use the memory addresses from 0 to 3, or 4 bytes).
There are some important things we have to take note of here. The numbers 0, 1, and 2 are all solely for illustrative purposes, and bear no relationship to the address values the computer will use in reality. In particular, the series of addresses are in reality going to be separated by some number of bytes that separate each address, and that separation may even exceed the size of the value being stored.
After foo() is over, its frame is deallocated:
| Address | Name | Value |
|---|---|---|
| 0 | x | 42 |
And then, after main(), even this last value goes away. Easy!
It’s called a ‘stack’ because it works like a stack of dinner plates: the first plate you put down is the last plate to pick back up. Stacks are sometimes called ‘last in, first out queues’ for this reason, as the last value you put on the stack is the first one you retrieve from it.
Let’s try a three-deep example:
fn italic() { let i = 6; } fn bold() { let a = 5; let b = 100; let c = 1; italic(); } fn main() { let x = 42; bold(); }
Okay, first, we call main():
| Address | Name | Value |
|---|---|---|
| 0 | x | 42 |
Next up, main() calls bold():
| Address | Name | Value |
|---|---|---|
| 3 | c | 1 |
| 2 | b | 100 |
| 1 | a | 5 |
| 0 | x | 42 |
And then bold() calls italic():
| Address | Name | Value |
|---|---|---|
| 4 | i | 6 |
| 3 | c | 1 |
| 2 | b | 100 |
| 1 | a | 5 |
| 0 | x | 42 |
Whew! Our stack is growing tall.
After italic() is over, its frame is deallocated, leaving only bold() and main():
| Address | Name | Value |
|---|---|---|
| 3 | c | 1 |
| 2 | b | 100 |
| 1 | a | 5 |
| 0 | x | 42 |
And then bold() ends, leaving only main():
| Address | Name | Value |
|---|---|---|
| 0 | x | 42 |
And then we’re done. Getting the hang of it? It’s like piling up dishes: you add to the top, you take away from the top.
The Heap
Now, this works pretty well, but not everything can work like this. Sometimes, you need to pass some memory between different functions, or keep it alive for longer than a single function’s execution. For this, we can use the heap.
In Rust, you can allocate memory on the heap with the Box<T> type.
⭐ All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box
. A box is a smart pointer to a heap allocated value of type T. When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed.
⭐ Boxed values can be dereferenced using the * operator; this removes one layer of indirection.
Here’s an example:
fn main() { let x = Box::new(5); let y = 42; }
| Address | Name | Value |
|---|---|---|
| 1 | y | 42 |
| 0 | x | ?????? |
A Box is a special kind of pointer that points to the heap, but it is still a pointer.
Knowing that, you understand that:
- Box
is 8 bytes because i8 is sized, - Box<&[i8]> is 8 bytes because a reference is sized,
- Box<[i8]> is 16 bytes because a slice is unsized.
We allocate space for two variables on the stack. y is 42, as it always has been, but what about x? Well, x is a Box
| Address | Name | Value |
|---|---|---|
| (2 ** 30) -1 | 5 | |
| .... | ... | ... |
| 1 | y | 42 |
| 0 | x | → (2 ** 30) - 1 |
We have (2 ** 30) addresses in our hypothetical computer with 1GB of RAM. And since our stack grows from zero, the easiest place to allocate memory is from the other end. So our first value is at the highest place in memory. And the value of the struct at x has a raw pointer to the place we’ve allocated on the heap, so the value of x is (2 ** 30) - 1, the memory location we’ve asked for.
We haven’t really talked too much about what it actually means to allocate and deallocate memory in these contexts. Getting into very deep detail is out of the scope of this tutorial, but what’s important to point out here is that the heap isn’t a stack that grows from the opposite end. We’ll have an example of this later in the book, but because the heap can be allocated and freed in any order, it can end up with ‘holes’. Here’s a diagram of the memory layout of a program which has been running for a while now:
| Address | Name | Value |
|---|---|---|
| (2 ** 30) -1 | 5 | |
| (2 ** 30) -2 | ||
| (2 ** 30) -3 | ||
| (2 ** 30) -4 | 42 | |
| .... | ... | ... |
| 2 | z | → (2 ** 30) - 4 |
| 1 | y | 42 |
| 0 | x | → (2 ** 30) - 1 |
In this case, we’ve allocated four things on the heap, but deallocated two of them. There’s a gap between (230) - 1 and (230) - 4 which isn’t currently being used. The specific details of how and why this happens depends on what kind of strategy you use to manage the heap. Different programs can use different ‘memory allocators’, which are libraries that manage this for you. Rust programs use jemalloc for this purpose.
Anyway, back to our example. Since this memory is on the heap, it can stay alive longer than the function which allocates the box. In this case, however, it doesn’t.2 When the function is over, we need to free the stack frame for main(). Box<T>, though, has a trick up its sleeve: Drop. The implementation of Drop for Box deallocates the memory that was allocated when it was created. Great! So when x goes away, it first frees the memory allocated on the heap:
| Address | Name | Value |
|---|---|---|
| 1 | y | 42 |
| 0 | x | ?????? |
We can make the memory live longer by transferring ownership, sometimes called ‘moving out of the box’. More complex examples will be covered later.