</>CodexBash
All articles
Programming

Stack vs heap memory

Where a program's data lives: the call stack with its frames for local variables, the heap for objects that outlive a function call, how C, C++, Java and Python use each, stack overflow and recursion, heap allocation costs and fragmentation, and common bugs such as dangling pointers and leaks.

CodexBash, , 6 min read

Every running program divides its memory into regions with different jobs. Two of them come up constantly, in error messages, interviews and performance discussions: the stack and the heap. The stack holds each function call's local variables and is managed automatically and very quickly; the heap holds data that must outlive a single call and is managed by the programmer or a garbage collector. Understanding the difference explains why deep recursion crashes with a "stack overflow", why returning a pointer to a local variable in C is a bug, and why Java objects are always reached through references. This article explains both.

Sign in to read the rest

The whole 6 minute article is free with an account, along with every problem, lesson and tutorial. No card.