The following code make a stackoverflow error:
int f(){
return f();
}
But are there any other ways to make a stackoverflow error?
(Thanks in advance)
The following code make a stackoverflow error:
int f(){
return f();
}
But are there any other ways to make a stackoverflow error?
(Thanks in advance)
Here's another way to throw a StackOverflowError, without overflowing the stack:
int f()
{
throw new StackOverflowError();
}
Another way is to have a method call another method, which calls that method The following will produce a StackOverflowError:
public static void main(String[] args)
{
testMethod();
}
public static void testMethod()
{
testMethod2();
}
public static void testMethod2()
{
testMethod();
}
In theory you might be able reduce the stack size (e.g -Xss1k
) and try to overflow the stack by declaring too many primitive variables.
However the minimum stack size I can set is 70k. Otherwise I get the error The stack size specified is too small, Specify at least 108k
(error doesn't appear between 80k - 107k+, though)
Any recursive method will generate an overflow error, if recursive depth is large (or deep?) enough. Your method is the perfect example, as it will generate unlimited depth.
There is no other way that I am aware of that doesn't include recursion and which is practically possible.
If you declare an Array that is too large, you will get an OutOfMemoryError, because the Array is not stored on the Stack but the Heap.
Local variables take up Stack space, but you cannot declare so many local variables (e.g. int i1 = 1; int i2 = 2; ... int i99999 = 99999; ...), because you are limited to 65536 characters.
You could try to "manually" call too many methods, e.g. int f1() { return f2(); } int f2(){ return f3();} ... but that would be basically the same as doing the recursion that you already mentioned.
Opening too many Threads also won't work, as each Thread is assigned it's own Stack. You will only get an OutOfMemoryError like with the Array.