Choosing stack vs heap affects lifetime, performance, and bug surface. Contrast with Java where most objects live on the heap under GC.
Stack characteristics
- Fast allocation/deallocation tied to function calls
- Limited size—deep recursion or huge locals can overflow
- Do not return pointers to local stack variables
Heap characteristics
- Flexible size and lifetime across functions
- Requires
malloc/freediscipline - Fragmentation and leaks if mismanaged
Important interview questions and answers
- Q: Return local array?
A: Invalid—stack memory dies when the function returns; return heap memory or use caller-provided buffer. - Q: When prefer stack?
A: Small, short-lived values with known bounded size.
Self-check
- Why is returning &local_int dangerous?
- What error indicates stack overflow?
Pitfall: Never return a pointer to a local stack variable—the memory is invalid after the function returns. Use heap allocation or caller-provided buffers.
Interview prep
- Return local array?
Invalid—the stack frame is destroyed on return; use heap allocation or caller buffer.