Junior — Middle
What methods exist for causing a stack overflow during program execution?
sobes.tech AI
Answer from AI
Stack overflow in C# is usually caused by infinite or excessively deep recursion. Main methods that lead to stack overflow:
- Infinite recursion: a function calls itself without an exit condition.
void Recursive()
{
Recursive(); // call without exit condition
}
Recursive();
-
Deep recursion: recursive calls with a large number of nested calls exceeding the stack size.
-
Creating large local variables: declaring very large local arrays or structures can lead to stack overflow, but this is less common.
Stack overflow results in a StackOverflowException in .NET, which cannot be caught or handled in code.