简体   繁体   中英

Recursive Summation Stack Overflow

I wrote a Java recursive method that calculates the summation of n from 0 to n. Here's the code:

private static long sum (long n) {
    if (n == 0) {
        return 0;
    } else {
        return n + sum(n-1);
    }
}

When I pass a large number such as 11000 and above, a stack overflow happens sometimes. Yes, I said sometimes. When n is greater than or equals to 11000 the program runs and either gives me the answer or a stack overflow.

Can anyone explain what's going on?

Consider using a For- Loop instead

public static long sum(long n) {
    long result = 0;
    for (int i = 1; i <= n; i++) {
        result += i;
    }
    return result;
}

Or of course, you can just use a fancy formula :) Thanks @Andy Turner

public static long sum(long n) {
    return n * (n + 1) / 2;
}

The reason you get a StackOverflow exception is because you're generating a call stack waaay bigger than the JVM expects.

Every time you call a method, you need to allocate space on the call stack for that method call in order to store references to local variables and method parameters and such.

The stack is at the top of the address space and is allocated from top to bottom. At the bottom of the address space is the heap, which is allocated from bottom to top. Once the method has been dealt with, it is popped off the stack.

Basically your method will continue to allocate memory on the stack with each call, and the stack will eventually run into the heap if there are too many calls. At that point, you are trying to claim memory that is already being used and you end up with a segmentation fault in the form of a stack overflow.

This is part of the reason why recursive implementation is generally discouraged most of the time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM