Junior — Middle
Can you explain what happens during a stack overflow in a program?
sobes.tech AI
Answer from AI
Stack overflow occurs when the call stack exceeds its limit, usually due to infinite or very deep recursion. Each function call adds a new frame to the stack, and if there is no base case or exit condition, the stack keeps growing.
In Java, this results in a StackOverflowError. To prevent this, ensure that recursive functions have proper base cases and do not call themselves indefinitely.
Example of infinite recursion:
public class StackOverflowExample {
public static void recursive() {
recursive(); // call itself without exit condition
}
public static void main(String[] args) {
recursive();
}
}
To avoid stack overflow, always include a termination condition in recursive functions or convert recursive algorithms to iterative ones.