Skip to main content
Engineering LibreTexts

10.15: Preventing Stack Overflows with a Base Case

  • Page ID
    14676
    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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 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; a detailed edit history is available upon request.

    • Was this article helpful?