Will this ever result in a stack overflow error?

北城以北 提交于 2019-12-08 18:12:31

Stack overflow? No, but it could lead to an integer overflow which is a very different thing.

A stack overflow means that space on the method invocation stack is exhausted (possibly because of a runaway recursive call). An integer overflow will cause the int to circle around to its lowest value if incremented beyond its maximum value.

In Java, a stack overflow error comes from excessive recursion. This is where a function calls itself, either directly or indirectly.

In your first example, the StackOverflow function directly calls itself without bound.

In your Dice example, there is no instance where a function calls itself, so you are not likely to encounter a stack overflow error.

A stack overflow error is caused by infinite recursion, that is, a method calling itself too many times. Your second code example doesn't seem to use recursion at all, so I don't think a stack overflow error is possible.

Will this ever result in a stack overflow error?

  • yes

Simply put:

Stack overflow is thrown when a stack overflow occurs because an application recurses too deeply. That means your line StackOverflow(x+1) ; can throw a stack overflow error depends on how big your stack is. Apart from that the code will start getting unexpected int values.

Well, you can change the maximum size of a stack in java with the -Xss switch. The smallest stack is about 1KB, so you wouldn't need infinite (or even very much) recursion to get the desired stack overflow, but you'd definitely need more than you've given in your example. I guess my point is that recursion is sufficient, but not necessary, to cause stack overflow; with an arbitrarily small call stack you could overflow it with an arbitrarily small number of method calls.

This will lead you to Integer overflow because int types goes from approx. -2E7 to 2E7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!