user3884215
user3884215

Reputation:

Why doesn't a stack overflow always occur?

I'm currently studying Java and, as a part of my learning, I attempted to intentionally induce a stack overflow to see what it would do.

I did some boundary testing and, interestingly, I discovered that if I execute the following code it will only sporadically cause an error. Sometimes it will run without any problems.

public class SO
{
    public static void main(String[] args)
    {
        ohno(0);
    }

    public static void ohno(int a)
    {
        System.out.println(a);
        if (a != 11413)
            ohno(a+1);
    }
}

My questions are as follows:

Upvotes: 6

Views: 217

Answers (3)

Caleb
Caleb

Reputation: 124997

Many compilers detect tail recursive calls and reuse the same stack frame for that call, thus preventing the such calls from growing the stack. A tail recursive call is one where the recursive call is the last instruction in a method or function. This optimization lets you use tail recursion without worrying about stack overflow.

If you want to induce an overflow, try adding some code after the recursive call to prevent the optimization. You might have to play with it a bit -- good compilers are crafty and may be able to subvert simple attempts.

Upvotes: 0

Steve Fan
Steve Fan

Reputation: 3361

The chance of occurring the StackOverflowException is depending on how much memory you have assigned, by using the parameters XmxM/G for the maximum memory and XmxS/G for the least.

Stack overflow could be happening on any situation, if there is a dead loop, or would have potential to get this by self looping with a large sum(that drains a lot of memories) of data.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160171

Limited stack size is a function of how much memory you allocate to the JVM.

Resource-constrained systems have less memory that can be allocated, so absolutely there are real-world scenarios where stack size is a limitation, and there are times where you have to use iterative solutions to naturally-recursive problems as a result.

Increasing the physical memory of a system only matters if you allow that memory to be allocated by the JVM, otherwise you'll get the defaults of that platform.

Upvotes: 3

Related Questions