<!doctype html><htmllang=endir=ltrclass="blog-wrapper blog-post-page plugin-blog plugin-id-default"data-has-hydrated=false><metacharset=UTF-8><metaname=generatorcontent="Docusaurus v3.6.1"><titledata-rh=true>Allocations in Rust: Foreword | The Old Speice Guy</title><metadata-rh=truename=viewportcontent="width=device-width,initial-scale=1.0"><metadata-rh=truename=twitter:cardcontent=summary_large_image><metadata-rh=trueproperty=og:urlcontent=https://speice.io/2019/02/understanding-allocations-in-rust><metadata-rh=trueproperty=og:localecontent=en><metadata-rh=truename=docusaurus_localecontent=en><metadata-rh=truename=docusaurus_tagcontent=default><metadata-rh=truename=docsearch:languagecontent=en><metadata-rh=truename=docsearch:docusaurus_tagcontent=default><metadata-rh=trueproperty=og:titlecontent="Allocations in Rust: Foreword | The Old Speice Guy"><metadata-rh=truename=descriptioncontent="There's an alchemy of distilling complex technical topics into articles and videos that change the"><metadata-rh=trueproperty=og:descriptioncontent="There's an alchemy of distilling complex technical topics into articles and videos that change the"><metadata-rh=trueproperty=og:typecontent=article><metadata-rh=trueproperty=article:published_timecontent=2019-02-04T12:00:00.000Z><linkdata-rh=truerel=iconhref=/img/favicon.ico><linkdata-rh=truerel=canonicalhref=https://speice.io/2019/02/understanding-allocations-in-rust><linkdata-rh=truerel=alternatehref=https://speice.io/2019/02/understanding-allocations-in-rusthreflang=en><linkdata-rh=truerel=alternatehref=https://speice.io/2019/02/understanding-allocations-in-rusthreflang=x-default><scriptdata-rh=truetype=application/ld+json>{"@context":"https://schema.org","@id":"https://speice.io/2019/02/understanding-allocations-in-rust","@type":"BlogPosting","author":{"@type":"Person","name":"Bradlee Speice"},"dateModified":"2024-11-10T02:05:00.000Z","datePublished":"2019-02-04T12:00:00.000Z","description":"There's an alchemy of distilling complex technical topics into articles and videos that change the","headline":"Allocations in Rust: Foreword","isPartOf":{"@id":"https://speice.io/","@type":"Blog","name":"Blog"},"keywords":[],"mainEntityOfPage":"https://speice.io/2019/02/understanding-allocations-in-rust","name":"Allocations in Rust: Foreword","url":"https://speice.io/2019/02/understanding-allocations-in-rust"}</script><linkrel=alternatetype=application/rss+xmlhref=/rss.xmltitle="The Old Speice Guy RSS Feed"><linkrel=alternatetype=application/atom+xmlhref=/atom.xmltitle="The Old Speice Guy Atom Feed"><linkrel=stylesheethref=/katex/katex.min.css><linkrel=stylesheethref=/assets/css/styles.16c3428d.css><scriptsrc=/assets/js/runtime~main.29a27dcf.jsdefer></script><scriptsrc=/assets/js/main.d461af80.jsdefer></script><bodyclass=navigation-with-keyboard><script>!function(){vart,e=function(){try{returnnewURLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}}()||function(){try{returnwindow.localStorage.getItem("theme")}catch(t){}}();t=null!==e?e:"light",document.documentElement.setAttribute("data-theme",t)}(),function(){try{for(var[t,e]ofnewURLSearchParams(window.location.search).entries())if(t.startsWith("docusaurus-data-")){vara=t.replace("docusaurus-data-","data-");document.documentElement.setAttribute(a,e)}}catch(t){}}()</script><divid=__docusaurus><divrole=regionaria-label="Skip to main content"><aclass=skipToContent_fXgnhref=#__docusaurus_skipToContent_fallback>Skip to main content</a></div><navaria-label=Mainclass="navbar navbar--fixed-top"><divclass=navbar__inner><divclass=navbar__items><buttonaria-label="Toggle navigation bar"aria-expanded=falseclass="navbar__toggle clean-btn"type=button><svgwidth=30height=30viewBox="0 0 30 30"aria-hidden=true><pathstroke=currentColorstroke-linecap=roundstroke-miterlimit=10stroke-width=2d="M4 7h22M4 15h22M4 23h22"/></svg></button><aclass=navbar__brandhref=/><divclass=navbar__logo><imgsrc=/img/logo.svgalt="Sierpinski Gasket"class=
way programmers see the tools they interact with on a regular basis. I knew what a linker was, but
there's a staggering amount of complexity in between
<ahref="https://www.youtube.com/watch?v=dOfucXtyEsU"target=_blankrel="noopener noreferrer">the OS and <code>main()</code></a>. Rust programmers use the
<ahref=https://doc.rust-lang.org/stable/std/boxed/struct.Box.htmltarget=_blankrel="noopener noreferrer"><code>Box</code></a> type all the time, but there's a
rich history of the Rust language itself wrapped up in
<ahref=https://manishearth.github.io/blog/2017/01/10/rust-tidbits-box-is-special/target=_blankrel="noopener noreferrer">how special it is</a>.</p>
<p>In a similar vein, this series attempts to look at code and understand how memory is used; the
complex choreography of operating system, compiler, and program that frees you to focus on
functionality far-flung from frivolous book-keeping. The Rust compiler relieves a great deal of the
cognitive burden associated with memory management, but we're going to step into its world for a
while.</p>
<p>Let's learn a bit about memory in Rust.</p>
<hr>
<p>Rust's three defining features of
<ahref=https://www.rust-lang.org/target=_blankrel="noopener noreferrer">Performance, Reliability, and Productivity</a> are all driven to a great
degree by the how the Rust compiler understands memory usage. Unlike managed memory languages (Java,
and the ownership system to ensure you can't accidentally corrupt memory. It's not as fast, but it
is important to have available.</p>
<p>That said, there are specific situations in Rust where you'd never need to worry about the
stack/heap distinction! If you:</p>
<ol>
<li>Never use <code>unsafe</code></li>
<li>Never use <code>#![feature(alloc)]</code> or the <ahref=https://doc.rust-lang.org/alloc/index.htmltarget=_blankrel="noopener noreferrer"><code>alloc</code> crate</a></li>
</ol>
<p>...then it's not possible for you to use dynamic memory!</p>
<p>For some uses of Rust, typically embedded devices, these constraints are OK. They have very limited
memory, and the program binary size itself may significantly affect what's available! There's no
operating system able to manage this
<ahref=https://en.wikipedia.org/wiki/Virtual_memorytarget=_blankrel="noopener noreferrer">"virtual memory"</a> thing, but that's not an issue
because there's only one running application. The
<ahref=https://docs.rust-embedded.org/embedonomicon/preface.htmltarget=_blankrel="noopener noreferrer">embedonomicon</a> is ever in mind, and
interacting with the "real world" through extra peripherals is accomplished by reading and writing
to <ahref=https://bob.cs.sonoma.edu/IntroCompOrg-RPi/sec-gpio-mem.htmltarget=_blankrel="noopener noreferrer">specific memory addresses</a>.</p>
<p>Most Rust programs find these requirements overly burdensome though. C++ developers would struggle
without access to <ahref=https://en.cppreference.com/w/cpp/container/vectortarget=_blankrel="noopener noreferrer"><code>std::vector</code></a> (except those
hardcore no-STL people), and Rust developers would struggle without
<ahref=https://doc.rust-lang.org/std/vec/struct.Vec.htmltarget=_blankrel="noopener noreferrer"><code>std::vec</code></a>. But with the constraints above,
<code>std::vec</code> is actually a part of the
<ahref=https://doc.rust-lang.org/alloc/vec/struct.Vec.htmltarget=_blankrel="noopener noreferrer"><code>alloc</code> crate</a>, and thus off-limits. <code>Box</code>,
<code>Rc</code>, etc., are also unusable for the same reason.</p>
<p>Whether writing code for embedded devices or not, the important thing in both situations is how much
you know <em>before your application starts</em> about what its memory usage will look like. In embedded
devices, there's a small, fixed amount of memory to use. In a browser, you have no idea how large
<ahref=https://www.google.comtarget=_blankrel="noopener noreferrer">google.com</a>'s home page is until you start trying to download it. The
compiler uses this knowledge (or lack thereof) to optimize how memory is used; put simply, your code
runs faster when the compiler can guarantee exactly how much memory your program needs while it's
running. This series is all about understanding how the compiler reasons about your program, with an
emphasis on the implications for performance.</p>
<p>Now let's address some conditions and caveats before going much further:</p>
<ul>
<li>We'll focus on "safe" Rust only; <code>unsafe</code> lets you use platform-specific allocation API's
(<ahref=https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htmtarget=_blankrel="noopener noreferrer"><code>malloc</code></a>) that we'll
ignore.</li>
<li>We'll assume a "debug" build of Rust code (what you get with <code>cargo run</code> and <code>cargo test</code>) and
address (pun intended) release mode at the end (<code>cargo run --release</code> and <code>cargo test --release</code>).</li>
<li>All content will be run using Rust 1.32, as that's the highest currently supported in the
<ahref=https://godbolt.org/target=_blankrel="noopener noreferrer">Compiler Exporer</a>. As such, we'll avoid upcoming innovations like
<ahref=https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.mdtarget=_blankrel="noopener noreferrer">compile-time evaluation of <code>static</code></a>
that are available in nightly.</li>
<li>Because of the nature of the content, being able to read assembly is helpful. We'll keep it
simple, but I <ahref=https://stackoverflow.com/a/4584131/1454178target=_blankrel="noopener noreferrer">found</a> a
<ahref=https://stackoverflow.com/a/26026278/1454178target=_blankrel="noopener noreferrer">refresher</a> on the <code>push</code> and <code>pop</code>
<ahref=http://www.cs.virginia.edu/~evans/cs216/guides/x86.htmltarget=_blankrel="noopener noreferrer">instructions</a> was helpful while writing
this.</li>
<li>I've tried to be precise in saying only what I can prove using the tools (ASM, docs) that are
available, but if there's something said in error it will be corrected expeditiously. Please let
me know at <ahref=mailto:bradlee@speice.iotarget=_blankrel="noopener noreferrer">bradlee@speice.io</a></li>
</ul>
<p>Finally, I'll do what I can to flag potential future changes but the Rust docs have a notice worth
repeating:</p>
<blockquote>
<p>Rust does not currently have a rigorously and formally defined memory model.</p>