Glossary · Programming

Stack vs Heap

The stack holds short-lived function data in a fast, ordered structure, while the heap holds dynamically allocated data that can outlive a function call.

Updated October 6, 2026

The stack and the heap are two regions of memory a program uses. The stack stores function call frames, parameters and local variables in last-in, first-out order and is cleaned up automatically when a function returns. The heap stores dynamically allocated data whose size or lifetime is not known at compile time.

Why it matters

Stack allocation is very fast because it only moves a pointer, but the stack is small and fixed in size. Heap allocation is flexible and can hold large or long-lived data, but it is slower and must be freed, either manually or by a garbage collector. Understanding the difference explains errors such as stack overflow from runaway recursion, and it explains why returning a pointer to a local variable is a bug.

Example

void f(void) {
    int a = 5;                       // stack
    int *b = malloc(sizeof(int));    // b on stack, its target on heap
    *b = 7;
    free(b);                         // heap memory must be released
}

When f returns, a disappears automatically, but the allocated block would leak without free.

Common mistakes

  • Assuming everything in managed languages lives on the heap or everything on the stack; it varies by language and runtime.
  • Recursing without a base case, which exhausts the stack.
  • Returning the address of a local variable.

Get notified when this term updates

Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.

This page is general information written by our editorial team and updated when documentation changes. Servers and providers differ, so test changes safely first. See our editorial policy and disclaimer.