kota's memex

Many languages don't require you to think about the stack and the heap very often. But in a systems languages like Rust, whether a value is on the stack or the heap affects how the language behaves and why you make certain decisions.

The stack stores values in the order it gets them and removes them in the opposite order. Also knows as last in, first out. You put more plates on a stack and when you need a new plate you grab it off the top.

All data stored in the stack must be a known fixed size. Data with an unknown size at compile time or a size that might change must be stored on the heap instead. Generally, reading and writing to the stack is many times faster than the heap.

The heap is less organized: when you put data on the heap you request a certain amount of space. The memory allocator finds an empty spot in the heap that is big enough, marks it as being in use, and returns a pointer to that location. This is called allocating or allocating to the heap as opposed to pushing to the stack.

Because the pointer to a location on the heap is itself a known fixed size you can store the pointer on the stack, but when you want the data it points to you must follow the pointer.

Keeping track of what parts of code are using what data on the heap, minimizing the amount of duplicate data on the heap, and cleaning up unused data on the heap so that you don't run out of space are all problems that the ownership model addresses.