What decides whether a piece of data lives on the stack or the heap, and why does it matter for performance?

technical-conceptual · Mid level · software-engineering

What the interviewer is really asking

Tests whether the candidate understands the stack/heap distinction in terms of lifetime and allocation mechanics — not just 'stack is fast' — and can connect it to real failure modes like stack overflow and heap fragmentation.

What to say

What to avoid

Example answers

Strong: Placement follows lifetime and size. A local with a known size that dies at function return goes on the stack — allocation is just bumping the stack pointer, so it's near-free and freed automatically. Anything that must outlive the call or whose size is only known at runtime goes on the heap, which costs an allocator lookup and explicit or GC-driven cleanup. The stack is bounded, so deep recursion overflows it; the heap fragments under long-running churn. In a managed runtime, escape analysis can even promote a heap object to the stack.

Weak: The stack is for small fast stuff and the heap is for big objects. The stack is faster, so you want to keep things on the stack when you can, and the heap is where dynamic memory goes.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.