java.lang.StackOverflowError due to recursion

前端 未结 10 2279
南方客
南方客 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

    In most cases, a stack overflow occurs because a recursive method was ill-defined, with a non-existent or unreachable ending condition, which causes the stack memory space to be exhausted. A correctly written recursion should not produce a stack overflow.

    However, there are situations where a method can produce a stack overflow even if it was correctly implemented. For instance:

    • A fast-growing (say, exponential) recursion. For example: the naive recursive implementation of the Fibonacci function
    • A very big input data, that will eventually cause the stack space to be exhausted

    Bottom line: it all depends on the particular case, it's impossible to generalize regarding what causes a stack overflow.

提交回复
热议问题