notes

Log | Files | Refs

stack-and-heap.txt (1391B)


      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 # Heap
     11 
     12 The heap is a region of a computer's memory used for dynamic memory allocation —
     13 memory that is reserved and released at runtime rather than at compile time. It
     14 is one of the two main memory areas programs use (alongside the stack), and it
     15 gives programmers flexible control over how much memory to use and for how long.
     16 
     17 ## Heap vs. Stack
     18 
     19 | Feature           | Heap                         | Stack                 |
     20 | :---------------- | :--------------------------- | :-------------------- |
     21 | Allocation timing | Runtime (dynamic)            | Compile time (static) |
     22 | Size              | Large, flexible              | Small, fixed          |
     23 | Management        | Manual or GC                 | Automatic (LIFO)      |
     24 | Access scope      | Global (anywhere in program) | Local to function     |
     25 | Speed             | Slightly slower              | Faster                |
     26 | Risk              | Memory leaks, fragmentation  | Stack overflow        |
     27 
     28 The stack follows a strict last-in, first-out (LIFO) structure, making it fast
     29 but limited. The heap is more flexible but requires careful management — failure
     30 to deallocate memory causes **memory leaks**, where memory becomes permanently
     31 unavailable.