stack-and-heap.md (1470B)
1 # Stack and Heap 2 3 # Stack 4 5 ## Call Stack 6 7 A region of memory the CPU uses automatically to track function calls, memory 8 pointers, local variables, and return addresses 9 10 ## Rust-specific rule 11 12 [Borrowing Rules](../memory_safety/borrowing_rules.md) 13 14 # Heap 15 16 The heap is a region of a computer's memory used for dynamic memory allocation — 17 memory that is reserved and released at runtime rather than at compile time. It 18 is one of the two main memory areas programs use (alongside the stack), and it 19 gives programmers flexible control over how much memory to use and for how long. 20 21 ## Heap vs. Stack 22 23 | Feature | Heap | Stack | 24 | :---------------- | :--------------------------- | :-------------------- | 25 | Allocation timing | Runtime (dynamic) | Compile time (static) | 26 | Size | Large, flexible | Small, fixed | 27 | Management | Manual or GC | Automatic (LIFO) | 28 | Access scope | Global (anywhere in program) | Local to function | 29 | Speed | Slightly slower | Faster | 30 | Risk | Memory leaks, fragmentation | Stack overflow | 31 32 The stack follows a strict last-in, first-out (LIFO) structure, making it fast 33 but limited. The heap is more flexible but requires careful management — failure 34 to deallocate memory causes **memory leaks**, where memory becomes permanently 35 unavailable.