Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 564935689ab5527f955e5449ded02799 > files > 173

rust-doc-1.19.0-1.mga6.armv7hl.rpm

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>The Stack and the Heap - The Rust Programming Language</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <base href="">

        <link rel="stylesheet" href="book.css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

        <link rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">

        <!-- MathJax -->
        <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

        <!-- Fetch JQuery from CDN but have a local fallback -->
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
            if (typeof jQuery == 'undefined') {
                document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
            }
        </script>
    </head>
    <body class="light">
        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme = localStorage.getItem('theme');
            if (theme == null) { theme = 'light'; }
            $('body').removeClass().addClass(theme);
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var sidebar = localStorage.getItem('sidebar');
            if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
            else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
        </script>

        <div id="sidebar" class="sidebar">
            <ul class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong>1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong>2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong>3.</strong> Syntax and Semantics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> if</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong>3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong>3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong>3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong>3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong>3.12.</strong> Structs</a></li><li><a href="enums.html"><strong>3.13.</strong> Enums</a></li><li><a href="match.html"><strong>3.14.</strong> Match</a></li><li><a href="patterns.html"><strong>3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong>3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong>3.17.</strong> Strings</a></li><li><a href="generics.html"><strong>3.18.</strong> Generics</a></li><li><a href="traits.html"><strong>3.19.</strong> Traits</a></li><li><a href="drop.html"><strong>3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong>3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong>3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong>3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong>3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong>3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong>3.26.</strong> <code>const</code> and <code>static</code></a></li><li><a href="attributes.html"><strong>3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong>3.28.</strong> <code>type</code> aliases</a></li><li><a href="casting-between-types.html"><strong>3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong>3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong>3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong>3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong>3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong>3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong>3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong>3.36.</strong> <code>unsafe</code></a></li></ul></li><li><a href="effective-rust.html"><strong>4.</strong> Effective Rust</a></li><li><ul class="section"><li><a href="the-stack-and-the-heap.html" class="active"><strong>4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong>4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong>4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html"><strong>4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong>4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong>4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong>4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong>4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong>4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong>4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong>4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong>4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong>4.13.</strong> Procedural Macros (and custom derive)</a></li></ul></li><li><a href="glossary.html"><strong>5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong>6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong>7.</strong> Bibliography</a></li></ul>
        </div>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <div id="menu-bar" class="menu-bar">
                    <div class="left-buttons">
                        <i id="sidebar-toggle" class="fa fa-bars"></i>
                        <i id="theme-toggle" class="fa fa-paint-brush"></i>
                    </div>

                    <h1 class="menu-title">The Rust Programming Language</h1>

                    <div class="right-buttons">
                        <i id="print-button" class="fa fa-print" title="Print this book"></i>
                    </div>
                </div>

                <div id="content" class="content">
                    <a class="header" href="the-stack-and-the-heap.html#the-stack-and-the-heap" id="the-stack-and-the-heap"><h1>The Stack and the Heap</h1></a>
<p>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.</p>
<p>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.</p>
<a class="header" href="the-stack-and-the-heap.html#memory-management" id="memory-management"><h1>Memory management</h1></a>
<p>These two terms are about memory management. The stack and the heap are
abstractions that help you determine when to allocate and deallocate memory.</p>
<p>Here’s a high-level comparison:</p>
<p>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.</p>
<a class="header" href="the-stack-and-the-heap.html#the-stack" id="the-stack"><h1>The Stack</h1></a>
<p>Let’s talk about this Rust program:</p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    let x = 42;
}
</code></pre></pre>
<p>This program has one variable binding, <code>x</code>. 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?</p>
<p>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
<code>main()</code> 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.</p>
<p>When the function exits, its stack frame gets deallocated. This happens
automatically as well.</p>
<p>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.</p>
<p>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:</p>
<pre><pre class="playpen"><code class="language-rust">fn foo() {
    let y = 5;
    let z = 100;
}

fn main() {
    let x = 42;

    foo();
}
</code></pre></pre>
<p>This program has three variables total: two in <code>foo()</code>, one in <code>main()</code>. Just
as before, when <code>main()</code> is called, a single integer is allocated for its stack
frame. But before we can show what happens when <code>foo()</code> 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 <code>0</code> to <code>1,073,741,823</code>. That
number comes from 2<sup>30</sup>, the number of bytes in a gigabyte. <sup class="footnote-reference"><a href="the-stack-and-the-heap.html#gigabyte">1</a></sup></p>
<div class="footnote-definition" id="gigabyte"><sup class="footnote-definition-label">1</sup>
<p>‘Gigabyte’ can mean two things: 10<sup>9</sup>, or 2<sup>30</sup>. The IEC standard resolved this by stating that ‘gigabyte’ is 10<sup>9</sup>, and ‘gibibyte’ is 2<sup>30</sup>. However, very few people use this terminology, and rely on context to differentiate. We follow in that tradition here.</p>
<p>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:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value </td></tr></thead>
<tr><td> 0       </td><td> x    </td><td> 42    </td></tr>
</table>
<p>We’ve got <code>x</code> located at address <code>0</code>, with the value <code>42</code>.</p>
<p>When <code>foo()</code> is called, a new stack frame is allocated:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value </td></tr></thead>
<tr><td> 2       </td><td> z    </td><td> 100   </td></tr>
<tr><td> 1       </td><td> y    </td><td> 5     </td></tr>
<tr><td> 0       </td><td> x    </td><td> 42    </td></tr>
</table>
<p>Because <code>0</code> was taken by the first frame, <code>1</code> and <code>2</code> are used for <code>foo()</code>’s
stack frame. It grows upward, the more functions we call. Notice that we are <strong>not</strong>
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).</p>
</div>
<p>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.</p>
<p>After <code>foo()</code> is over, its frame is deallocated:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value </td></tr></thead>
<tr><td> 0       </td><td> x    </td><td> 42    </td></tr>
</table>
<p>And then, after <code>main()</code>, even this last value goes away. Easy!</p>
<p>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.</p>
<p>Let’s try a three-deep example:</p>
<pre><pre class="playpen"><code class="language-rust">fn italic() {
    let i = 6;
}

fn bold() {
    let a = 5;
    let b = 100;
    let c = 1;

    italic();
}

fn main() {
    let x = 42;

    bold();
}
</code></pre></pre>
<p>We have some kooky function names to make the diagrams clearer.</p>
<p>Okay, first, we call <code>main()</code>:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value </td></tr></thead>
<tr><td> 0       </td><td> x    </td><td> 42    </td></tr>
</table>
<p>Next up, <code>main()</code> calls <code>bold()</code>:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value </td></tr></thead>
<tr><td> <strong>3</strong>   </td><td> <strong>c</strong></td><td><strong>1</strong>  </td></tr>
<tr><td> <strong>2</strong>   </td><td> <strong>b</strong></td><td><strong>100</strong></td></tr>
<tr><td> <strong>1</strong>   </td><td> <strong>a</strong></td><td> <strong>5</strong> </td></tr>
<tr><td> 0       </td><td> x    </td><td> 42    </td></tr>
</table>
<p>And then <code>bold()</code> calls <code>italic()</code>:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value </td></tr></thead>
<tr><td> <em>4</em>     </td><td> <em>i</em>  </td><td> <em>6</em>   </td></tr>
<tr><td> <strong>3</strong>   </td><td> <strong>c</strong></td><td><strong>1</strong>  </td></tr>
<tr><td> <strong>2</strong>   </td><td> <strong>b</strong></td><td><strong>100</strong></td></tr>
<tr><td> <strong>1</strong>   </td><td> <strong>a</strong></td><td> <strong>5</strong> </td></tr>
<tr><td> 0       </td><td> x    </td><td> 42    </td></tr>
</table>
<p>Whew! Our stack is growing tall.</p>
<p>After <code>italic()</code> is over, its frame is deallocated, leaving only <code>bold()</code> and
<code>main()</code>:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value </td></tr></thead>
<tr><td> <strong>3</strong>   </td><td> <strong>c</strong></td><td><strong>1</strong>  </td></tr>
<tr><td> <strong>2</strong>   </td><td> <strong>b</strong></td><td><strong>100</strong></td></tr>
<tr><td> <strong>1</strong>   </td><td> <strong>a</strong></td><td> <strong>5</strong> </td></tr>
<tr><td> 0       </td><td> x    </td><td> 42    </td></tr>
</table>
<p>And then <code>bold()</code> ends, leaving only <code>main()</code>:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value </td></tr></thead>
<tr><td> 0       </td><td> x    </td><td> 42    </td></tr>
</table>
<p>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.</p>
<a class="header" href="the-stack-and-the-heap.html#the-heap" id="the-heap"><h1>The Heap</h1></a>
<p>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.</p>
<p>In Rust, you can allocate memory on the heap with the <a href="../../std/boxed/index.html"><code>Box&lt;T&gt;</code> type</a>.
Here’s an example:</p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    let x = Box::new(5);
    let y = 42;
}
</code></pre></pre>
<p>Here’s what happens in memory when <code>main()</code> is called:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value  </td></tr></thead>
<tr><td> 1       </td><td> y    </td><td> 42     </td></tr>
<tr><td> 0       </td><td> x    </td><td> ?????? </td></tr>
</table>
<p>We allocate space for two variables on the stack. <code>y</code> is <code>42</code>, as it always has
been, but what about <code>x</code>? Well, <code>x</code> is a <code>Box&lt;i32&gt;</code>, and boxes allocate memory
on the heap. The actual value of the box is a structure which has a pointer to
‘the heap’. When we start executing the function, and <code>Box::new()</code> is called,
it allocates some memory for the heap, and puts <code>5</code> there. The memory now looks
like this:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 5                      </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 1                    </td><td> y    </td><td> 42                     </td></tr>
<tr><td> 0                    </td><td> x    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
</table>
<p>We have (2<sup>30</sup>) 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 <code>x</code> has a <a href="raw-pointers.html">raw pointer</a> to the place we’ve
allocated on the heap, so the value of <code>x</code> is (2<sup>30</sup>) - 1, the memory
location we’ve asked for.</p>
<p>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:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 5                      </td></tr>
<tr><td> (2<sup>30</sup>) - 2 </td><td>      </td><td>                        </td></tr>
<tr><td> (2<sup>30</sup>) - 3 </td><td>      </td><td>                        </td></tr>
<tr><td> (2<sup>30</sup>) - 4 </td><td>      </td><td> 42                     </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 2                    </td><td> z    </td><td> → (2<sup>30</sup>) - 4 </td></tr>
<tr><td> 1                    </td><td> y    </td><td> 42                     </td></tr>
<tr><td> 0                    </td><td> x    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
</table>
<p>In this case, we’ve allocated four things on the heap, but deallocated two of
them. There’s a gap between (2<sup>30</sup>) - 1 and (2<sup>30</sup>) - 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 <a href="http://www.canonware.com/jemalloc/">jemalloc</a> for this purpose.</p>
<p>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.<sup class="footnote-reference"><a href="the-stack-and-the-heap.html#moving">2</a></sup> When the function is over, we need to free the stack frame
for <code>main()</code>. <code>Box&lt;T&gt;</code>, though, has a trick up its sleeve: <a href="drop.html">Drop</a>. The
implementation of <code>Drop</code> for <code>Box</code> deallocates the memory that was allocated
when it was created. Great! So when <code>x</code> goes away, it first frees the memory
allocated on the heap:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value  </td></tr></thead>
<tr><td> 1       </td><td> y    </td><td> 42     </td></tr>
<tr><td> 0       </td><td> x    </td><td> ?????? </td></tr>
</table>
<div class="footnote-definition" id="moving"><sup class="footnote-definition-label">2</sup>
<p>We can make the memory live longer by transferring ownership,
sometimes called ‘moving out of the box’. More complex examples will
be covered later.</p>
</div>
<p>And then the stack frame goes away, freeing all of our memory.</p>
<a class="header" href="the-stack-and-the-heap.html#arguments-and-borrowing" id="arguments-and-borrowing"><h1>Arguments and borrowing</h1></a>
<p>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:</p>
<pre><pre class="playpen"><code class="language-rust">fn foo(i: &amp;i32) {
    let z = 42;
}

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

    foo(y);
}
</code></pre></pre>
<p>When we enter <code>main()</code>, memory looks like this:</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value  </td></tr></thead>
<tr><td> 1       </td><td> y    </td><td> → 0    </td></tr>
<tr><td> 0       </td><td> x    </td><td> 5      </td></tr>
</table>
<p><code>x</code> is a plain old <code>5</code>, and <code>y</code> is a reference to <code>x</code>. So its value is the
memory location that <code>x</code> lives at, which in this case is <code>0</code>.</p>
<p>What about when we call <code>foo()</code>, passing <code>y</code> as an argument?</p>
<table><thead><tr><td> Address </td><td> Name </td><td> Value  </td></tr></thead>
<tr><td> 3       </td><td> z    </td><td> 42     </td></tr>
<tr><td> 2       </td><td> i    </td><td> → 0    </td></tr>
<tr><td> 1       </td><td> y    </td><td> → 0    </td></tr>
<tr><td> 0       </td><td> x    </td><td> 5      </td></tr>
</table>
<p>Stack frames aren’t only for local bindings, they’re for arguments too. So in
this case, we need to have both <code>i</code>, our argument, and <code>z</code>, our local variable
binding. <code>i</code> is a copy of the argument, <code>y</code>. Since <code>y</code>’s value is <code>0</code>, so is
<code>i</code>’s.</p>
<p>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.</p>
<a class="header" href="the-stack-and-the-heap.html#a-complex-example" id="a-complex-example"><h1>A complex example</h1></a>
<p>Okay, let’s go through this complex program step-by-step:</p>
<pre><pre class="playpen"><code class="language-rust">fn foo(x: &amp;i32) {
    let y = 10;
    let z = &amp;y;

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

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

    baz(e);
}

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

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

    foo(j);
}
</code></pre></pre>
<p>First, we call <code>main()</code>:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>We allocate memory for <code>j</code>, <code>i</code>, and <code>h</code>. <code>i</code> is on the heap, and so has a
value pointing there.</p>
<p>Next, at the end of <code>main()</code>, <code>foo()</code> gets called:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 5                    </td><td> z    </td><td> → 4                    </td></tr>
<tr><td> 4                    </td><td> y    </td><td> 10                     </td></tr>
<tr><td> 3                    </td><td> x    </td><td> → 0                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>Space gets allocated for <code>x</code>, <code>y</code>, and <code>z</code>. The argument <code>x</code> has the same value
as <code>j</code>, since that’s what we passed it in. It’s a pointer to the <code>0</code> address,
since <code>j</code> points at <code>h</code>.</p>
<p>Next, <code>foo()</code> calls <code>baz()</code>, passing <code>z</code>:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 7                    </td><td> g    </td><td> 100                    </td></tr>
<tr><td> 6                    </td><td> f    </td><td> → 4                    </td></tr>
<tr><td> 5                    </td><td> z    </td><td> → 4                    </td></tr>
<tr><td> 4                    </td><td> y    </td><td> 10                     </td></tr>
<tr><td> 3                    </td><td> x    </td><td> → 0                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>We’ve allocated memory for <code>f</code> and <code>g</code>. <code>baz()</code> is very short, so when it’s
over, we get rid of its stack frame:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 5                    </td><td> z    </td><td> → 4                    </td></tr>
<tr><td> 4                    </td><td> y    </td><td> 10                     </td></tr>
<tr><td> 3                    </td><td> x    </td><td> → 0                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>Next, <code>foo()</code> calls <code>bar()</code> with <code>x</code> and <code>z</code>:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> (2<sup>30</sup>) - 2 </td><td>      </td><td> 5                      </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 10                   </td><td> e    </td><td> → 9                    </td></tr>
<tr><td> 9                    </td><td> d    </td><td> → (2<sup>30</sup>) - 2 </td></tr>
<tr><td> 8                    </td><td> c    </td><td> 5                      </td></tr>
<tr><td> 7                    </td><td> b    </td><td> → 4                    </td></tr>
<tr><td> 6                    </td><td> a    </td><td> → 0                    </td></tr>
<tr><td> 5                    </td><td> z    </td><td> → 4                    </td></tr>
<tr><td> 4                    </td><td> y    </td><td> 10                     </td></tr>
<tr><td> 3                    </td><td> x    </td><td> → 0                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>We end up allocating another value on the heap, and so we have to subtract one
from (2<sup>30</sup>) - 1. It’s easier to write that than <code>1,073,741,822</code>. In any
case, we set up the variables as usual.</p>
<p>At the end of <code>bar()</code>, it calls <code>baz()</code>:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> (2<sup>30</sup>) - 2 </td><td>      </td><td> 5                      </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 12                   </td><td> g    </td><td> 100                    </td></tr>
<tr><td> 11                   </td><td> f    </td><td> → (2<sup>30</sup>) - 2 </td></tr>
<tr><td> 10                   </td><td> e    </td><td> → 9                    </td></tr>
<tr><td> 9                    </td><td> d    </td><td> → (2<sup>30</sup>) - 2 </td></tr>
<tr><td> 8                    </td><td> c    </td><td> 5                      </td></tr>
<tr><td> 7                    </td><td> b    </td><td> → 4                    </td></tr>
<tr><td> 6                    </td><td> a    </td><td> → 0                    </td></tr>
<tr><td> 5                    </td><td> z    </td><td> → 4                    </td></tr>
<tr><td> 4                    </td><td> y    </td><td> 10                     </td></tr>
<tr><td> 3                    </td><td> x    </td><td> → 0                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>With this, we’re at our deepest point! Whew! Congrats for following along this
far.</p>
<p>After <code>baz()</code> is over, we get rid of <code>f</code> and <code>g</code>:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> (2<sup>30</sup>) - 2 </td><td>      </td><td> 5                      </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 10                   </td><td> e    </td><td> → 9                    </td></tr>
<tr><td> 9                    </td><td> d    </td><td> → (2<sup>30</sup>) - 2 </td></tr>
<tr><td> 8                    </td><td> c    </td><td> 5                      </td></tr>
<tr><td> 7                    </td><td> b    </td><td> → 4                    </td></tr>
<tr><td> 6                    </td><td> a    </td><td> → 0                    </td></tr>
<tr><td> 5                    </td><td> z    </td><td> → 4                    </td></tr>
<tr><td> 4                    </td><td> y    </td><td> 10                     </td></tr>
<tr><td> 3                    </td><td> x    </td><td> → 0                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>Next, we return from <code>bar()</code>. <code>d</code> in this case is a <code>Box&lt;T&gt;</code>, so it also frees
what it points to: (2<sup>30</sup>) - 2.</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 5                    </td><td> z    </td><td> → 4                    </td></tr>
<tr><td> 4                    </td><td> y    </td><td> 10                     </td></tr>
<tr><td> 3                    </td><td> x    </td><td> → 0                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>And after that, <code>foo()</code> returns:</p>
<table><thead><tr><td> Address              </td><td> Name </td><td> Value                  </td></tr></thead>
<tr><td> (2<sup>30</sup>) - 1 </td><td>      </td><td> 20                     </td></tr>
<tr><td> ...                  </td><td> ...  </td><td> ...                    </td></tr>
<tr><td> 2                    </td><td> j    </td><td> → 0                    </td></tr>
<tr><td> 1                    </td><td> i    </td><td> → (2<sup>30</sup>) - 1 </td></tr>
<tr><td> 0                    </td><td> h    </td><td> 3                      </td></tr>
</table>
<p>And then, finally, <code>main()</code>, which cleans the rest up. When <code>i</code> is <code>Drop</code>ped,
it will clean up the last of the heap too.</p>
<a class="header" href="the-stack-and-the-heap.html#what-do-other-languages-do" id="what-do-other-languages-do"><h1>What do other languages do?</h1></a>
<p>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 <code>Drop</code> to clean up memory, the garbage collector deals with the heap
instead.</p>
<a class="header" href="the-stack-and-the-heap.html#which-to-use" id="which-to-use"><h1>Which to use?</h1></a>
<p>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.</p>
<p>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.</p>
<a class="header" href="the-stack-and-the-heap.html#runtime-efficiency" id="runtime-efficiency"><h2>Runtime Efficiency</h2></a>
<p>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.</p>
<p>If you’d like to dive into this topic in greater detail, <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.143.4688">this paper</a>
is a great introduction.</p>
<a class="header" href="the-stack-and-the-heap.html#semantic-impact" id="semantic-impact"><h2>Semantic impact</h2></a>
<p>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 <code>Rc&lt;T&gt;</code> and <code>Arc&lt;T&gt;</code>, is one example of this).</p>
<p>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).</p>

                </div>

                <!-- Mobile navigation buttons -->
                
                    <a href="effective-rust.html" class="mobile-nav-chapters previous">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="testing.html" class="mobile-nav-chapters next">
                        <i class="fa fa-angle-right"></i>
                    </a>
                

            </div>

            
                <a href="effective-rust.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-left"></i>
                </a>
            

            
                <a href="testing.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-right"></i>
                </a>
            

        </div>


        <!-- Local fallback for Font Awesome -->
        <script>
            if ($(".fa").css("font-family") !== "FontAwesome") {
                $('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
            }
        </script>

        <!-- Livereload script (if served using the cli tool) -->
        

        <script src="highlight.js"></script>
        <script src="book.js"></script>
    </body>
</html>