What is a StackOverflowError, what causes it and how should I handle it?

What is a StackOverflowError, what causes it and how should I handle it?

Parameters and local variables are allocated on the stack (for reference types, the object is on the heap and a variable on the stack refers to this object on the heap). The stack is usually located at the top of your address space and when it is used up, it moves to the bottom of the address space (i.e. towards zero).

Your process also has a heap, which is located at the bottom of your process. If you allocate memory, this heap can grow to the top of your address space. As you can see, there is a possibility that the heap "collides" with the stack.

The most common cause of a stack overflow is an incorrect recursive call. Usually this is caused when your recursive function does not have the right termination condition, so it keeps calling itself. Or if the termination condition is fine, it can be caused by requiring too many recursive calls before the condition is met.

However, in GUI programming, it is possible to create indirect recursion. For example, your application can process image messages and call a function during processing that causes the system to send another image message. You did not explicitly call this function yourself, but the OS /VM did it for you.

To deal with this, you need to examine your code. If you have functions that call themselves, then check to see if there is a termination condition. If so, then check to see if you changed at least one of the arguments when you called the function. Otherwise, there is no visible change for the recursively called function and the termination condition is useless. Also remember that memory on your stack may run out before a valid termination condition is reached. Therefore, make sure that your method can handle input values that require further recursive calls.

If you do not have any obvious recursive functions, then check to see if you are calling any library functions that indirectly cause your function to be called (as in the implicit case above).

package com.company;

public class StackOverflowExample {

    static int i = 0;

    public static int printNumber(int x)
    {

        i = i + 2;
        System.out.println(i);
        return i + printNumber(i + 2);
    }

    public static void main(String[] args)
    {
        StackOverflowExample.printNumber(i);
    }
}

Share this Post