Memory: Stack & Heap
How a running program uses memory — call stack frames, heap allocation, pointers vs references, garbage collection and common memory bugs.
Every running program divides its memory into regions. Two of them matter most day to day: the stack, which tracks function calls, and the heap, which holds data whose size or lifetime isn't known ahead of time. Knowing which is which explains stack overflows, memory leaks, why objects are "passed by reference", and how garbage collectors work.
The call stack
Each function call pushes a stack frame holding its parameters, local variables and return address. Returning pops the frame. Allocation is just moving the stack pointer, so it's extremely fast, and cleanup is automatic.
int square(int x) {
int r = x * x;
return r;
}
int main() {
int a = 4;
int b = square(a); // a frame for square is pushed, then popped
return b;
}def square(x):
r = x * x
return r
def main():
a = 4
b = square(a)
return bfunction square(x: number): number {
const r = x * x;
return r;
}
function main() {
const a = 4;
const b = square(a);
return b;
}Stack overflow: the stack is small (typically 512 KB–8 MB per thread). Very deep or infinite recursion exhausts it: StackOverflowError in Java, RecursionError in Python (which limits depth to about 1000 by default), RangeError: Maximum call stack size exceeded in JS.
The heap
The heap is a large pool for data that must outlive the function that created it, or whose size is decided at runtime: objects, arrays, strings, lists. Allocation is slower (the allocator has to find space) and something must eventually free the memory.
| Stack | Heap | |
|---|---|---|
| Holds | Frames: locals, parameters, return addresses | Objects, arrays, dynamically sized data |
| Lifetime | Until the function returns | Until freed or garbage-collected |
| Allocation | Move a pointer — very fast | Allocator search — slower |
| Size | Small, fixed per thread | Large, grows as needed |
| Threads | One stack per thread | Shared by all threads |
| Failure | Stack overflow | Out of memory, fragmentation, leaks |
Values vs references
In Java, Python and JavaScript, variables that hold objects store a reference (an address) to a heap object. Assigning or passing the variable copies the reference, not the object.
int[] a = {1, 2, 3};
int[] b = a; // same array
b[0] = 99;
System.out.println(a[0]); // 99
void reset(int[] arr) { arr = new int[3]; } // reassigns the local copy only
reset(a); // a is unchangeda = [1, 2, 3]
b = a # same list
b[0] = 99
print(a[0]) # 99
def reset(lst):
lst = [] # rebinds the local name only
reset(a) # a is unchanged
c = a.copy() # a new list (shallow copy)const a = [1, 2, 3];
const b = a; // same array
b[0] = 99;
console.log(a[0]); // 99
const c = [...a]; // shallow copy
const d = structuredClone(a); // deep copyWho frees heap memory?
| Approach | How it works | Languages | Trade-offs |
|---|---|---|---|
| Manual | You call free / delete | C, C++ (raw) | Fast and predictable; easy to leak or double-free |
| RAII / smart pointers | Freed when the owner goes out of scope | C++ (unique_ptr), Rust | No GC pauses; Rust checks ownership at compile time |
| Reference counting | Free when the count of references hits 0 | Python (plus a cycle collector), Swift | Immediate cleanup; cycles need extra handling |
| Tracing GC | Periodically find everything reachable from roots; free the rest | Java, JS, Go, C# | Safe and easy; pauses and memory overhead |
Tracing garbage collection in one picture
The collector starts from roots (stack variables, globals, registers), marks every object it can reach, and reclaims the rest. Most collectors are generational: most objects die young, so new objects are collected frequently and cheaply, and survivors are promoted to an old generation collected rarely.
Common memory bugs
- Memory leak — memory that's no longer needed stays reachable. In GC languages: ever-growing caches or maps, listeners never removed, closures holding large objects.
- Dangling pointer / use-after-free (C/C++) — using memory after freeing it. A major source of security vulnerabilities.
- Buffer overflow (C/C++) — writing past the end of an array and overwriting neighbouring memory.
- Double free — freeing the same memory twice.
- Stack: per-thread frames for calls and locals; fast, automatic, small.
- Heap: shared, for objects with dynamic size or lifetime; needs freeing.
- Object variables hold references; assignment copies the reference.
- Memory is freed manually, by ownership (RAII/Rust), by reference counting, or by tracing GC.
- Leaks happen in GC languages too: anything reachable is kept.
QWhere are local variables and objects stored in Java?easy
Local primitives and references live in the thread's stack frame. Objects (anything created with new, including arrays) live on the heap. The JIT's escape analysis can sometimes avoid heap allocation for objects that never leave a method.
QCan a Java program have a memory leak?medium
Yes. The GC frees only unreachable objects. A static map that keeps growing, listeners that are registered but never removed, or a ThreadLocal in a thread pool all keep objects reachable forever.
QWhy is the stack faster than the heap?medium
Stack allocation is a single pointer adjustment, frees happen automatically in reverse order, and the top of the stack is almost always in cache. Heap allocation has to find a free block, may need synchronisation between threads, and must eventually be reclaimed.