Course contentsShow
← Computer Science
Lesson 2081 of 2,87247. Memory Management in LanguagesFree lesson

Stack vs Heap: Lifetime and Scope

Stack variables live until function returns; heap objects persist until explicitly freed or garbage collected.

Stack vs Heap: Lifetime and Scope

You'll learn: How long variables live depending on whether they're stored on the stack or heap, and what that means for your program's memory behavior.

The Core Difference

When you allocate memory on the stack, that memory has a built-in expiration date: it automatically disappears when the function that created it returns. Stack variables live within their function's scope and die when that scope ends.

When you allocate memory on the heap, that memory persists beyond any single function call. It stays alive until you explicitly free it (in languages like C) or until a garbage collector reclaims it (in languages like Java or Python).

Why This Matters

Think of stack allocation like borrowing a hotel room for the night—you use it, then automatically check out when your stay ends. Heap allocation is like buying a house—it's yours until you sell it (explicit deallocation) or someone forecloses on it (garbage collection).

Stack Lifetime Example

When a function calls another function, the new stack frame is pushed on. When that function returns, its entire frame—including all local variables—is popped off instantly. No manual cleanup needed.

Heap Lifetime Characteristics

Heap-allocated objects can outlive the function that created them. You might allocate memory in one function and pass a pointer/reference to another part of your program that uses it much later. This flexibility comes with responsibility: someone must eventually free that memory.

This difference affects design decisions: use the stack for temporary, function-scoped data; use the heap when data needs to survive across function calls or when you don't know its lifetime at compile time.

Key Takeaway: Stack memory is automatically managed with lifetime tied to function scope; heap memory persists until explicitly freed or garbage collected, allowing data to outlive its creating function.