Memory: Stack & Heap

How a running program uses memory — call stack frames, heap allocation, pointers vs references, garbage collection and common memory bugs.

Beginner 4 min readLesson 6 of 8 Interview Q&A

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;
}
square: x = 4, r = 16← topmain: a = 4, b = ?
While square runs, its frame sits on top of main's.

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.

StackHeappoints tostack frame: mainp = 0x7a10 (reference)Person objectname: "Ada" · age: 36String "Ada"
StackHeap
HoldsFrames: locals, parameters, return addressesObjects, arrays, dynamically sized data
LifetimeUntil the function returnsUntil freed or garbage-collected
AllocationMove a pointer — very fastAllocator search — slower
SizeSmall, fixed per threadLarge, grows as needed
ThreadsOne stack per threadShared by all threads
FailureStack overflowOut 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 unchanged

Who frees heap memory?

ApproachHow it worksLanguagesTrade-offs
ManualYou call free / deleteC, C++ (raw)Fast and predictable; easy to leak or double-free
RAII / smart pointersFreed when the owner goes out of scopeC++ (unique_ptr), RustNo GC pauses; Rust checks ownership at compile time
Reference countingFree when the count of references hits 0Python (plus a cycle collector), SwiftImmediate cleanup; cycles need extra handling
Tracing GCPeriodically find everything reachable from roots; free the restJava, 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.

rootsABCDE
Green: reachable, kept. Red: unreachable (even though D and E reference each other), collected.

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.
Key takeaways
  • 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.
Interview questions
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.