The Stack and the heap are abstractions that help you determine when to allocate and deallocate memory.
High-level comparison
-
The stack is very fast, and where memory is allocated in Rust by default.
-
allocation is local to a function call and is limited in size.
-
The heap is slower, and is explicitly allocated by your program.
- but it's "effectively" unlimited in size and globally accessible.
in Rust:
This code for an example:
fn main() {
let x = 42;
}
rust stack allocates x
by default.
when a function gets called, memory is allocated for all variables or info in the function scope.
This is called a stack frame.
so our single 32-bit integer is allocated to the stack. when the function exits, it's values get deallocated from the stack automatically.
stack allocation is very, very fast.
we can move fast because we automatically can allocated and deallocate all at once.
but since this deallocation: downside is that we can't keep values around if we need them for longer than a single scope/function
what does the 'stack' really mean?
fn foo() {
let y = 5;
let z = 100;
}
fn main() {
let x = 42;
foo();
}
2 values in foo()
1 in main()
but...
How does Computer Memory Work?
if you have one gig of RAM: 0 -> 1,073,741,823
or 2^30 or 10^9
I have 16GB of RAM so that would be 0 -> 17,179,869,184
memory is like a giant array so the stack frame we made with main()
would be:
Address | Name | Value |
---|---|---|
0 | x | 42 |
we got x located at address: 0 with value of 42
when we call foo()
the stack now looks like:
Address | Name | Value |
---|---|---|
2 | z | 100 |
1 | y | 5 |
0 | x | 42 |
the only thing we are not taking into account is the size
of the stack frame which would be based on the value and it's type.
after foo()
is called, is frame address: 0 is deallocated.
stacks are LIFO queues.
"What is the Heap" -> Next...