10.15: Preventing Stack Overflows with a Base Case
- Page ID
- 14676
In order to prevent stack overflow bugs, you must have a base case where the function stops make new recursive calls. If there is no base case then the function calls will never stop and eventually a stack overflow will occur. Here is an example of a recursive function with a base case. The base case is when the param
parameter equals 2.
def fizz(param): print(param) if param == 2: return fizz(param - 1) fizz(5)
When you run this program, the output will look like this:
5 4 3 2
This program does not have a stack overflow error because once the param parameter is set to 2
, the if
statement’s condition will be True
and the function will return, and then the rest of the calls will also return in turn.
Though if your code never reaches the base case, then this will cause a stack overflow. If we changed the fizz(5)
call to fizz(0)
, then the program’s output would look like this:
File "C:\rectest.py", line 5, in fizz fizz(param - 1) File "C:\rectest.py", line 5, in fizz fizz(param - 1) File "C:\rectest.py", line 5, in fizz fizz(param - 1) File "C:\rectest.py", line 2, in fizz print(param) RuntimeError: maximum recursion depth exceeded
Recursive calls and base cases will be used to perform the flood fill algorithm, which is described next.