繁体   English   中英

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

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

我将无限递归函数定义为:

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

然后我调用了函数,这发生了:

>>> 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
>>>

接下来我这样做:

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

然后我再次调用该函数,但是...

>>> 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

我想知道,将递归限制更改为 2147483647 后,为什么 Python 仍然将递归限制为 1000?

递归限制已成功更新,因为第一条错误消息是:

RecursionError: maximum recursion depth exceeded

然后在增加递归深度后,错误信息变为:

MemoryError: Stack overflow

sys.setrecursionlimit()上的文档:

将 Python 解释器堆栈的最大深度设置为 limit。 此限制可防止无限递归导致 C 堆栈溢出和 Python 崩溃。

因此,通过增加递归限制,程序使 Python 解释器崩溃。

由于 Python 没有优化尾递归,无限递归会导致堆栈溢出(内存不足)。

在许多现实世界的应用程序中,有必要实现没有递归的函数,以避免堆栈溢出内存错误。

另请参阅:在 python 脚本中设置堆栈大小

暂无
暂无

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

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