Sobes.tech
Junior — Middle

What can lead to stack overflow in a program?

sobes.tech AI

Answer from AI

Stack overflow occurs when the call stack overflows due to too deep recursion or infinite function calls.

Main causes:

  • Infinite recursion — a function calls itself without an exit condition.
  • Too deep recursion — even with an exit condition, the recursion depth is too large (e.g., when processing large data structures).
  • Cyclic function calls — functions call each other in a loop without an exit.

Example of infinite recursion in C#:

void Recursive()
{
    Recursive(); // no exit condition
}

Recursive();

To avoid stack overflow, always have a correct exit condition in recursion or use iterative algorithms if the call depth can be large.