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