Backend Basics

Understanding the Call Stack and Stack Traces

By LineStacks Editorial Team · · 4 min read

Every programmer eventually meets a wall of text after something crashes: dozens of lines naming files, functions and line numbers. It looks intimidating, and many beginners scroll past it to search for the last line only. That wall of text is a stack trace, and it is one of the most useful debugging tools you have.

To read it well, you first need to understand the call stack, the structure it describes.

What the Call Stack Is

When your program calls a function, the computer needs to remember where to return when that function finishes. It also needs space for the function's local variables. The call stack is the memory structure that keeps track of both.

Each active function call gets a block on the stack called a stack frame. The frame holds the function's arguments, local variables and the return location. When a function calls another, a new frame is placed on top. When a function returns, its frame is removed, and execution continues in the frame below.

The word stack describes the order: last in, first out. Think of a pile of plates. You add to the top and remove from the top.

A Walkthrough

Consider this short Python program.

def load_config(name):
    return read_file(name)

def read_file(name):
    with open(name) as f:
        return f.read()

def start():
    config = load_config("settings.txt")
    print(config)

start()

When the program runs, the stack grows step by step.

  1. The main program calls start. Stack: start.
  2. start calls load_config. Stack: start, load_config.
  3. load_config calls read_file. Stack: start, load_config, read_file.
  4. read_file calls open, which finishes or fails.

At the deepest point, three of your own functions are waiting on one another. As each returns, its frame is popped, and the program steps back down.

What a Stack Trace Is

If something goes wrong and an error is raised, the runtime can capture the stack at that moment. A stack trace is a printed snapshot of those frames, showing the chain of calls that led to the problem.

If settings.txt does not exist, Python prints something like this.

Traceback (most recent call last):
  File "app.py", line 11, in <module>
    start()
  File "app.py", line 7, in start
    config = load_config("settings.txt")
  File "app.py", line 2, in load_config
    return read_file(name)
  File "app.py", line 5, in read_file
    with open(name) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'settings.txt'

Each pair of lines shows a file, a line number, a function name and the code on that line.

How to Read It

Reading order depends on the language, so check which way yours prints. Python lists the oldest call first and the most recent last, as the header "most recent call last" states. Java and JavaScript print the error message first, followed by the most recent call at the top and older callers below.

A reliable approach works in any language.

  1. Read the error type and message first. It states what went wrong, such as a missing file, a null value or a type mismatch.
  2. Find the frame where the error was raised. This is the exact line that failed.
  3. Look at the frames around it that belong to your code. Library frames show the path through frameworks, but the bug is more often in the code you wrote.
  4. Walk outward through callers. Ask what values were passed in. The line that failed may be correct, with a bad argument supplied further up the chain.

In the example, the failure is on the open line, but the real cause is that the program was started in a folder without that file, or the name was wrong.

Common Stack Problems

Stack overflow. The stack has a limited size. If a function calls itself without a proper stopping condition, frames pile up until the limit is hit and the program fails with a stack overflow or recursion error. The trace shows the same few lines repeating many times.

def countdown(n):
    return countdown(n - 1)

The fix is a base case that ends the recursion, or rewriting the logic as a loop.

Deep but valid recursion. Some legitimate algorithms, such as walking a very deep tree, can exceed limits. An iterative version with an explicit list of pending work avoids the problem.

Lost context in asynchronous code. With callbacks, promises or tasks, the original caller may no longer be on the stack when the error occurs. Traces can look short or confusing. Many runtimes offer an option to record asynchronous stack traces, which is worth enabling during development.

Getting More From Traces

  • Log full traces, not only the message, when handling errors in production. A message such as "failed" with no trace is nearly useless.
  • Do not swallow exceptions. Catching an error and discarding it destroys the trace. If you must wrap an error, keep the original attached.
  • Use a debugger. Pausing at a breakpoint lets you see the live call stack and inspect variables in each frame.
  • Keep functions small. Short, well-named functions make traces read like a story.
  • Be careful with sensitive data. Traces and logs can reveal file paths and values, so do not show them to end users.

Frequently Asked Questions

What is the difference between the call stack and the heap?

The stack holds function frames and local variables, and is managed automatically as functions are called and return. The heap holds objects that live longer and are allocated on demand, and is managed by the runtime or the programmer.

Why does my stack trace not show my code?

The error may have been raised deep inside a library or in asynchronous code. Scroll through the frames to find the first one that points to your files, since that is where your code called into the failing part.

Can a stack trace tell me the root cause?

It shows where the failure happened and how the program got there, which usually narrows the search a great deal. The root cause may still be an earlier wrong value, so check what was passed down the chain.

Related reading