The Heap helps pass some memory between functions or keep memory alive for longer than a single function’s execution.
you can allocate memory on the heap with Rust with the [[Box
How does memory look when main() is called
Address | Name | Value |
---|---|---|
1 | y | 42 |
0 | x | ???? |
now the value of x is Box<i32> | ||
which is a pointer to the heap |
the value only gets assigned during execution.
and to make sure it doesn’t collide with the stack, it allocates the memory on the other end of our computer’s list of accessible memory addresses (RAM).
so my computer’s stack looks like this:
Address | Name | Value |
---|---|---|
16 * (2^30) - 1 | 5 | |
… | … | … |
1 | y | 42 |
0 | x | :LiArrowBigRight: 16 * (2^30) - 1 |
just know that the Heap is not deallocated in order like the Stack, it can deallocate without order.
Rust will still deallocate the memory from the heap, but you can keep the memory allocated by transferring ownership.