Two situations. First, when the data must outlive the function that creates it, e.g. you build a structure in one function and return it for use elsewhere; a stack local would be destroyed on return, so it has to be heap (or caller-provided, or static). Second, when the size is only known at runtime and is potentially large, reading a file whose length you discover at runtime, or a buffer sized from a packet's length field. Large allocations also belong on the heap because the stack is small and bounded; a multi-kilobyte buffer as a stack local risks overflow. Conversely, you should not use the heap for small, short-lived data that fits the natural scope, that's what the stack is for, and it's free and automatic. In hard-real-time or safety-critical embedded code, you often avoid the heap entirely and pre-allocate statically.
C Programming · Interview question
When would you choose the heap over the stack?
A strong answer
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.