Skip to main content
CSArchitecture & RuntimeDiagramBeginner

Stack vs Heap Memory

KO: 스택 vs 힙 메모리·EN: Stack vs Heap Memory·JA: スタック vs ヒープメモリ

Comparing fast, per-thread, LIFO-managed Stack memory against large, process-shared, dynamically allocated Heap memory

Table of Contents

Structure Diagram

Stack Memory vs Heap Memory Comparison
STACKStack Memory

Per-thread · Nanosecond pointer bump

  • AllocationFixed size · Automatic LIFO unwind
  • Speed & CacheFastest (single SP register bump, hot L1)
  • Size LimitSmall (~1–8MB per thread; Stack Overflow)
  • StoresCall frames, local primitives, references
HEAPHeap Memory

Process-shared · Dynamic large allocations

  • AllocationDynamic runtime alloc · GC or manual free
  • Speed & CacheSlower (allocator search, fragmentation)
  • Size LimitLarge (grows up to OS RAM/virtual limits)
  • StoresObjects, dynamic arrays, shared state
Quick Answer

What is Stack vs Heap Memory?

Comparing fast, per-thread, LIFO-managed Stack memory against large, process-shared, dynamically allocated Heap memory. It is a core concept in Architecture & Runtime within CS.

Core Principles

At runtime, a process's dynamic data lives in two distinct memory regions: the Stack and the Heap.

  • Stack: Private per thread. Allocating or freeing a frame is a single CPU stack-pointer instruction, yielding zero fragmentation and superb L1 cache locality.
  • Heap: Shared across all threads for dynamically sized or long-lived objects, managed by an allocator (malloc, jemalloc) plus either a GC, reference counter, or ownership system.

Practical Takeaways

  • Escape Analysis: Go and JVM JIT compilers automatically stack-allocate objects whose references never escape the creating function, eliminating GC overhead.
  • References vs Payloads: In Java/JS/Python, local references sit on the stack while the object payloads reside on the heap.
  • Avoid huge stack buffers: Allocating multi-MB fixed arrays as locals causes instant Stack Overflow—put large buffers on the heap.

Notable Examples

  • Rust Ownership: Stack by default, explicit heap via Box/Vec/String, deterministic cleanup without GC.
  • Go Profiling: Inspecting heap escapes with go build -gcflags="-m".