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.
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).
Function parameters, local variables, arrays, etc. live in stack memory is determined at compile time.
Heap memory is managed at runtime. When people talk about memory management, they mostly mean managing heap memory.
Tips and Traps on Stack Memory¶
The layout of a type is its size, alignment, and the relative offsets of its fields.
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.
The function std::mem:size_of returns the size of a type in bytes.
Stack overflow issues are often caused by
- infinite (or too deep) recursive functions
- too large array on stack
struct MyStruct{
r: u32,
s0: u8,
s1: u8,
s2: u8,
flag: u8,
}
std::mem::size_of::<MyStruct>()
Functions to Work with Rust Memory¶
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
std::ptr::copy
std::mem::copy
std::mem::swap
References¶
Stack, Heap, and Static Memory https://www.youtube.com/watch?v=NnLdGKoz1ls