Ben Chuanlong Du's Blog

It is never too late to learn.

Memory Layout in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Different Types of Memory in Rust

Rust has 3 different types of memory: static memory, stack memory and heap memory.

  1. Static variables live in static memory and is determined at compile time. It is suggested that you define large data variables as static so that they live in the static memory instead of stack memory to avoid stack overflow problems. Of course, another way is to put those variables into heap memory (but at the cost of slight performance loss).

  2. Function parameters, local variables, arrays, etc. live in stack memory is determined at compile time.

  3. Heap memory is managed at runtime. When people talk about memory management, they mostly mean managing heap memory.

Tips and Traps on Stack Memory

  1. The layout of a type is its size, alignment, and the relative offsets of its fields.

  2. The function std::mem::align_of_val returns the ABI-required minimum alignment of the type of the value that val points to in bytes. Every reference to a value of the type T must be a multiple of this number.

  3. The function std::mem:size_of returns the size of a type in bytes.

  4. Stack overflow issues are often caused by

    • infinite (or too deep) recursive functions
    • too large array on stack
In [10]:
struct MyStruct{
    r: u32,
    s0: u8,
    s1: u8,
    s2: u8,
    flag: u8,
}

std::mem::size_of::<MyStruct>()
Out[10]:
8

Functions to Work with Rust Memory

In [ ]:
std::mem::MaybeUninit
https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html

https://doc.rust-lang.org/nomicon/unchecked-uninit.html
Unchecked Uninitialized Memory
In [ ]:
std::ptr::copy

std::mem::copy

std::mem::swap
In [ ]:
 

Comments