Roadmap › How Computers Work — CPU, Memory, OS, Processes and Threads › Module: Memory
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| Stack | Heap | |
|---|---|---|
| Stores | Call frames: parameters, locals, return address | Objects (class instances, arrays, strings) |
| Allocation | Move a pointer — extremely fast | Find space — fast in .NET (bump pointer), but needs cleanup |
| Freed | Automatically when the method returns | By the garbage collector (.NET/Java) or manually (free/delete in C/C++) |
| Size | Small (1 MB per thread by default on Windows) | Large (limited by RAM/address space) |
| Per | Thread | Process (shared by all threads) |
| Errors | Stack 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 unreachableStack 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).