Stack and heap
When a program starts up, by default a 2 Mb chunk of memory called the stack is granted to it. The program will use its stack to store all its local variables and function parameters, for example an i32 variable takes 4 bytes on the stack. When our program calls a function, a new stack frame is allocated to it. Through this mechanism, the stack knows in which order functions are called, so that functions return correctly to the calling code, while possibly returning values.
Dynamically sized-types, like strings or vectors, can't be stored on the stack. For these values, a program can request memory space on its heap, which is a much bigger piece of memory than the stack.
When possible, stack allocation is preferred in Rust ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access