The Rust Model of Memory
202307102000
Status: #idea
Tags: Rust
The Rust Model of Memory
Variables live in the stack
- Variables live in frames. A frame is a mapping of variables to values, within a single scope (like a function)
- Frames are organised into a stack of currently called functions
- After a function returns, Rust deallocates the function's frame
Boxes live in the stack
- Rust uses pointers to transfer data without copying it
- A common way to make a pointer, is to allocate memory in the heap. The heap is a separate area of memory, where data can live indefinitely
Warning
Integer's which have a known size at compile time are stored entirely on the stack
Info
Rust uses a Box for putting data on the heap
A Box's owner manages deallocation
Box Deallocation Principle
If a variable owns a box, when Rust deallocates the variable's frame, then Rust also deallocates the box's heap memory.
Refer to this example to see how collections use boxes.
Variables Cannot Be Used After Being Moved
Refer to this example
Important
Refer to Quiz Q4 here
Undefined behaviour is caused due to multiple owners