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 over heap allocation, because accessing the stack is a lot more efficient.