Stack overflow in Java

From dftwiki3
Jump to: navigation, search

--D. Thiebaut (talk) 21:58, 29 November 2015 (EST)



This page contains a program written in Java that illustrates a stack overflow condition, and how to increase the size of the stack when running the program.

Source


// SumInts.java
// D. Thiebaut
//
// A demo program illustrating how one can set the
// stack size for a program that uses recursion and
// reaches deeper than the stack allows.
//
// Run the program as follows:
//
//    javac SumInts.java
//    java SumInts 1000
//
// The previous call will compute the sum of 1+2+3+4+...+1000
// Keep on increasing the command line parameter until stack
// overflow occurs.
// At this point, you can try increasing the stack size as 
// follows:
//
//    java -Xss8m SumInts 200000
//
// This will reserve 8MB of stack at start-up.
// The default stack size varies with the JVM and hosts.  
// Typically 512KB is used, but this will vary.


class SumInts{

    static public long sumIt( long n ) {
        if (n <= 1 )
            return 1;
        return n + sumIt( n-1 );
    }

    static public void main( String[] args ) {
        long n, res;
        if ( args.length == 0 ) {
            System.out.println( "Syntax: java SumInts n" );
            return;
        }
        n = Integer.parseInt( args[0] );
        res = sumIt( n );
        System.out.println( "n = " + n + " sum = " + res );
    }
}


Running the Program


[21:56:35] ~/Desktop$: javac SumInts.java
 
[21:56:35] ~/Desktop$: java SumInts 1000
n = 1000 sum = 500500
 
[21:56:43] ~/Desktop$: java SumInts 2000
n = 2000 sum = 2001000
 
[21:56:46] ~/Desktop$: java SumInts 4000
n = 4000 sum = 8002000
 
[21:56:49] ~/Desktop$: java SumInts 8000
n = 8000 sum = 32004000
 
[21:56:51] ~/Desktop$: java SumInts 16000
Exception in thread "main" java.lang.StackOverflowError
	at SumInts.sumIt(SumInts.java:29)
	at SumInts.sumIt(SumInts.java:31)
	at SumInts.sumIt(SumInts.java:31)
        ...
	at SumInts.sumIt(SumInts.java:31)
	at SumInts.sumIt(SumInts.java:31)
	at SumInts.sumIt(SumInts.java:31)
 
[21:56:54] ~/Desktop$: java -Xss4m SumInts 16000
n = 16000 sum = 128008000