10.15: Preventing Stack Overflows with a Base Case

Making Games with Python and Pygame · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    10.15: Preventing Stack Overflows with a Base Case

    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.


    This page titled 10.15: Preventing Stack Overflows with a Base Case was last modified on Mon, 18 May 2020 08:27:01 GMT and is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Al Sweigart via source content that was edited to the style and standards of the LibreTexts platform.