C Programming · Interview question

What's the difference between stack and heap allocation?

A strong answer

Stack storage holds local variables and parameters; it has automatic lifetime tied to scope, a local is created when its block is entered and destroyed when the block exits, managed entirely by the compiler via frame push/pop. It's extremely fast (just moving the stack pointer) but bounded by a fixed maximum size. Heap storage comes from malloc/calloc; it has manual lifetime, the block lives until you explicitly free it, so it can outlive the function that created it. The heap is flexible in size (decided at runtime) and large, but slower to allocate and subject to fragmentation. The rule of thumb: use the stack by default, use the heap only when the data must outlive its creating function or its size isn't known at compile time.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Stack vs Heap

Where your variables actually live: automatic stack storage vs manual heap allocation, and why returning a pointer to a local is the classic firmware crash.

More Stack vs Heap questions

Browse all 472 interview questions