java.lang.StackOverflowError due to recursion

前端 未结 10 2226
南方客
南方客 2020-12-03 05:59

My problem is that I usually get a java.lang.StackOverflowError when I use recursion. My question is - why does recursion cause stackoverflow so much more than loops do, and

相关标签:
10条回答
  • 2020-12-03 06:43

    Each recursive call uses some space on the stack (to house anything specific to that one call, such as arguments, local variables, etc.). Thus, if you make too many recursive calls (either by not correctly providing a base case or just by trying to do too many recursive calls), then there is not enough room to provide space for it all, and you end up with a StackOverflow.

    The reason why loops do not have this problem is that each iteration of a loop does not use its own unique space (i.e. if I loop n times, I don't need extra space to do the n+1st loop).

    0 讨论(0)
  • 2020-12-03 06:43

    The reason why the recursion causes stack overflow is because we fail to establish when the recursion should stop, and thus the function/method will keep calling itself "forever" (until it causes the error). You will have the same problem even if you are using loops, if you have something as the following:

    bool flag = true;
    while (flag == true){
       count++;
    }
    

    Since flag will always be true, the while loop will never stop until it gives you the stack overflow error.

    0 讨论(0)
  • 2020-12-03 06:46

    Here for loop is used inside the recursive function. When the recursive function is called, for(int i=0; i<n; i++) the value of i is initialized to zero, as it calls itself, the value of i will again be initialized to zero and it conitues infintely. This will lead you to Stack overflow error.

    Solution: Avoid for loop inside recursive function; instead go for while or do-while and initialize the value of i outside recursive function

    0 讨论(0)
  • 2020-12-03 06:48

    When properly used, recursion will not produce a StackOverflowError. If it does, then your base case is not being triggered, and the method keeps calling itself ad infinitum. Every method call that does not complete remains on the stack, and eventually it overflows.

    But loops don't involve method calls by themselves, so nothing builds up on the stack and a StackOverflowError does not result.

    0 讨论(0)
提交回复
热议问题