简体   繁体   English

为什么增加递归深度会导致堆栈溢出错误?

[英]Why does increasing the recursion depth result in stack overflow error?

I define a infinite recursive function as:我将无限递归函数定义为:

>>>def f():
>>>   f()
>>>

Then I called the function and this happend:然后我调用了函数,这发生了:

>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
File "<stdin>", line 2, in f
File "<stdin>", line 2, in f
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
>>>

Next I do this:接下来我这样做:

>>>import sys
>>>sys.getrecursionlimit()
1000
>>>sys.setrecursionlimit(2147483647) #as 2147483647 is the highest number I can set for recursion in Python 3.8.5

Then I again call the function, but...然后我再次调用该函数,但是...

>>> f()
Traceback (most recent call last):
File "<stdin>", line 2, in f
File "<stdin>", line 2, in f
File "<stdin>", line 2, in f
[Previous line repeated 997 more times]
MemoryError: Stack overflow

I want to know, after changing the recursion limit to 2147483647 , why Python is still restricting the recursion to 1000?我想知道,将递归限制更改为 2147483647 后,为什么 Python 仍然将递归限制为 1000?

The recursion limit was successfully updated, since the first errors message was:递归限制已成功更新,因为第一条错误消息是:

RecursionError: maximum recursion depth exceeded

and then after increasing the recursion depth, the error message changed to:然后在增加递归深度后,错误信息变为:

MemoryError: Stack overflow

From the documentation on sys.setrecursionlimit() :sys.setrecursionlimit()上的文档:

Set the maximum depth of the Python interpreter stack to limit.将 Python 解释器堆栈的最大深度设置为 limit。 This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.此限制可防止无限递归导致 C 堆栈溢出和 Python 崩溃。

Hence, by increasing the recursion limit, the program crashed the Python interpreter.因此,通过增加递归限制,程序使 Python 解释器崩溃。

Since Python does not optimize tail recursion, unlimited recursion causes the stack to overflow (run out of memory).由于 Python 没有优化尾递归,无限递归会导致堆栈溢出(内存不足)。

In many real-world applications it is necessary to implement functions without recursion to avoid stack overflow memory errors.在许多现实世界的应用程序中,有必要实现没有递归的函数,以避免堆栈溢出内存错误。

See also: Setting stacksize in a python script另请参阅:在 python 脚本中设置堆栈大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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