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?


computer memory = a massive list of memory addresses from 0 to a number that represents how much RAM you have.

if you have one gig of RAM: 0 -> 1,073,741,823 or 2^30 or 10

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:

AddressNameValue
0x42

we got x located at address: 0 with value of 42

when we call foo() the stack now looks like:

AddressNameValue
2z100
1y5
0x42

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…