C++ › Memory Management

What causes a stack overflow?

Intermediate

Answer

A stack overflow happens when the call stack exceeds its size limit—commonly from very deep or infinite recursion, or allocating very large local arrays/objects on the stack. It typically crashes the program. Fixes include converting recursion to iteration, reducing recursion depth, or allocating large data on the heap.
void recurse() { recurse(); } // infinite recursion -> stack overflow
Real-world example A recursive tree traversal on a deeply unbalanced tree overflows the stack and crashes.

Common follow-ups: How do you avoid stack overflow? | Why allocate large arrays on the heap?