Lessons in this course (11)

4. Stack vs heap — how program memory is laid out

Basic★ Must knowLesson 4 of 11

A process's virtual memory is split into regions:

text
High addresses
┌──────────────────────┐
│ Stack (per thread)    │  ← method calls, local variables, return addresses; grows down
│        ↓              │
│                       │
│        ↑              │
│ Heap                  │  ← objects created with new; managed by GC in .NET
├──────────────────────┤
│ Static/global data    │  ← static fields, constants
├──────────────────────┤
│ Code (text)           │  ← machine code (JIT output for .NET)
└──────────────────────┘
Low addresses
StackHeap
StoresCall frames: parameters, locals, return addressObjects (class instances, arrays, strings)
AllocationMove a pointer — extremely fastFind space — fast in .NET (bump pointer), but needs cleanup
FreedAutomatically when the method returnsBy the garbage collector (.NET/Java) or manually (free/delete in C/C++)
SizeSmall (1 MB per thread by default on Windows)Large (limited by RAM/address space)
PerThreadProcess (shared by all threads)
ErrorsStack overflow (deep/infinite recursion)Out of memory, leaks, fragmentation
csharp
void PlaceOrder()
{
    int qty = 3;                         // local value on the stack (inside PlaceOrder's frame)
    var order = new Order { Qty = qty }; // the reference 'order' is on the stack; the Order object is on the heap
    Save(order);                         // a new frame for Save is pushed on the stack
}                                        // frame popped: qty and the reference disappear; the Order object stays until GC finds it unreachable

Stack overflow example: int F(int n) => F(n + 1); — every call adds a frame until the 1 MB stack is full and the process crashes (in .NET a StackOverflowException cannot be caught).