6.3. Stack Trace#

Stack trace (also known as stack back track or stack trace back) is a list of the function calls, and their corresponding stack frames, at some point in the execution of a program.

Any time a program crashes, most programming languages will print a stack trace to the console. This is a list of all the functions that were called up to the point of the crash, and it is a very useful tool for debugging. By examining the stack trace, you can determine the sequence of function calls that led to the crash.

As an example, the following Python program contains an error.

def a():
    i = 0
    j = b(i)      # line 3
    return j

def b(z):
    k = 5
    if z == 0:
        c()       # line 9
    return k + z

def c():
    error()       # line 13

a()               # line 15
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [1], in <cell line: 15>()
     12 def c():
     13     error()       # line 13
---> 15 a()

Input In [1], in a()
      1 def a():
      2     i = 0
----> 3     j = b(i)      # line 3
      4     return j

Input In [1], in b(z)
      7 k = 5
      8 if z == 0:
----> 9     c()       # line 9
     10 return k + z

Input In [1], in c()
     12 def c():
---> 13     error()

NameError: name 'error' is not defined

6.4. Stack Overflow#

Stack overflow is a common problem in recursive programs. It occurs when the stack is full and there is no more space to push new function calls. In this notebook, we will also implement a simple stack overflow detection mechanism.

def f():
    f()

f()
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
Cell In[3], line 4
      1 def f():
      2     f()
----> 4 f()

Cell In[3], line 2, in f()
      1 def f():
----> 2     f()

Cell In[3], line 2, in f()
      1 def f():
----> 2     f()

    [... skipping similar frames: f at line 2 (2970 times)]

Cell In[3], line 2, in f()
      1 def f():
----> 2     f()

RecursionError: maximum recursion depth exceeded