Conceptcore
Call stack
Also called execution stack, run-time stack, control stack, program stack, machine stack, the stack.
The call stack holds one entry for each call that has not yet returned. A call pushes an entry and a return pops it, so the top is always the function that runs now.
- Applies to
- core-languages
Idea
When main calls a, a calls b and b calls c, the program must remember three places to go back to, in the reverse order. The call stack keeps them. Each call that has started and not yet returned has one entry on the stack, and the newest entry is on top. A call pushes an entry, and a return pops it and goes back to the caller. The top entry is the function that runs now, and the entries below it are the calls that wait for it.
import inspect
def where():
names = [f.function for f in inspect.stack()[1:]] # innermost first
return " <- ".join(n for n in names if n != "<module>")
def c():
print(" stack:", where())
def b():
print(" call c")
c()
print(" back in b")
def a():
print(" call b")
b()
print(" back in a")
def main():
print("call a")
a()
print("back in main")
main()
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
At the deepest point, four calls are active: c on top, and b, a and main below it. Each return pops one entry, so the program goes back to b, then to a, then to main, in the reverse order of the calls.
How it works
Push on call, pop on return. A call stack is "a stack data structure that stores information about the active subroutines" of a program1. The main reason for it "is to keep track of the point to which each active subroutine should return control when it finishes executing"1. The caller or the start of the called function "pushes the return address onto the stack, and the called subroutine, when it finishes, pulls or pops the return address off the call stack and transfers control to that address"1. MDN describes the JavaScript stack in the same way: "It's called a stack because it's last-in-first-out"2.
An entry is a frame. Each entry holds more than the return address. It also holds the arguments and the local variables of the call. This entry is a stack frame. In the Java Virtual Machine, "A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt"3. Because each call has its own frame, each call of a recursive function has its own copy of its locals.
Why recursion needs a stack. SICP shows the need with factorial. To compute n!, the machine must first compute (n - 1)!, and after that it still needs the old value of n. "In order to be able to continue the suspended computation, the machine must save the contents of any registers that will be needed after the subproblem is solved"4. A stack holds these saved values, one set for each call that waits. See recursion.
One stack for each thread. "There is usually exactly one call stack associated with a running program (or more accurately, with each task or thread of a process)"1. In Java, "Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread"3. When the stack has no more space for a push, "an error called a stack overflow occurs"1. See stack overflow.
Unwinding. A return pops one frame. An exception can pop many frames at once. "When an exception is thrown, the stack is unwound until a handler is found that is prepared to handle (catch) the type of the thrown exception"1. See exception handling.
Reading the stack. A debugger and a stack trace read the same data. In GDB, a backtrace "shows one line per frame, for many frames, starting with the currently executing frame (frame zero), followed by its caller (frame one), and on up the stack"5. The trace that a program prints when an exception is not caught is the call stack at the place of the throw. A profiler also samples the stack: "if a subroutine's address appears in the call stack sampling data many times, it is likely to act as a code bottleneck"1.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin on the JVM uses the JVM stack, and the program can read it with StackWalker or the stackTrace of a Throwable. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query has no call stack that the code can see. |
| Bash | Native | |
| PowerShell | Native | The Get-PSCallStack cmdlet shows the call stack of a script. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no calls. |
| CSS | Does not apply | CSS has no calls. |
| Regular expressions | Does not apply | A regular expression has no calls. |
| Language | Verdict | How the program reads its own stack |
|---|---|---|
| Python | native | inspect.stack(); the traceback module; frames are objects |
| JavaScript | native | the stack string of an Error, which is not in the standard |
| TypeScript | native | as in JavaScript |
| Java | native | StackWalker; Throwable.getStackTrace() |
| Kotlin | native | the JVM stack; StackWalker and Throwable.stackTrace from Java |
| C# | native | System.Diagnostics.StackTrace |
| Go | native | one stack for each goroutine; runtime.Callers and runtime.CallersFrames |
| Rust | native | std::backtrace::Backtrace |
| C | native | no standard function; a debugger such as GDB reads it |
| C++ | native | std::stacktrace |
| Bash | native | the FUNCNAME array and the caller builtin |
| PowerShell | native | Get-PSCallStack |
| SQL | n/a | a query has no call stack that the code can see |
| Regex | n/a | a pattern has no calls |
| HTML | n/a | HTML has no calls |
| CSS | n/a | CSS has no calls |
Every language with functions uses a call stack, but the languages give different access to it. Python's inspect.stack() returns a list of frame records: "The first entry in the returned list represents the caller; the last entry represents the outermost call on the stack"6. In JavaScript, the stack property of an error is "Non-standard", but it "is de facto implemented by all major JavaScript engines"7. Java's StackWalker reports frames "from the top most frame that represents the execution point at which the stack was generated to the bottom most frame"8. Go's runtime.Callers "fills the slice pc with the return program counters of function invocations on the calling goroutine's stack"9. C++ has std::basic_stacktrace, which "represents a snapshot of the whole stacktrace or its given part"10. In Bash, FUNCNAME is "An array variable containing the names of all shell functions currently in the execution call stack"11. In PowerShell, "The Get-PSCallStack cmdlet displays the current call stack"12.
The example files print the same trace in each language. Python, JavaScript, TypeScript, Java, C#, Go, Rust and Bash read the stack with the tools in the table. C and C++ keep their own list of names, which each function pushes on entry and pops on return.
import inspect
def where():
names = [f.function for f in inspect.stack()[1:]] # innermost first
return " <- ".join(n for n in names if n != "<module>")
def c():
print(" stack:", where())
def b():
print(" call c")
c()
print(" back in b")
def a():
print(" call b")
b()
print(" back in a")
def main():
print("call a")
a()
print("back in main")
main()
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native.
inspect.stack()returns one record for each frame, the caller first and the outermost call last. Each frame is an object, withf_backfor the frame of its caller.
#include <iostream>
#include <string>
#include <vector>
// The program keeps its own copy of the stack. A Frame pushes a name when it is
// made and pops it when it is destroyed, so every return pops it.
std::vector<std::string> names;
struct Frame {
explicit Frame(std::string name) { names.push_back(std::move(name)); }
~Frame() { names.pop_back(); }
};
std::string where() {
std::string out;
for (auto it = names.rbegin(); it != names.rend(); ++it) {
out += (out.empty() ? "" : " <- ") + *it;
}
return out;
}
void c() {
Frame f("c");
std::cout << " stack: " << where() << '\n';
}
void b() {
Frame f("b");
std::cout << " call c\n";
c();
std::cout << " back in b\n";
}
void a() {
Frame f("a");
std::cout << " call b\n";
b();
std::cout << " back in a\n";
}
int main() {
Frame f("main");
std::cout << "call a\n";
a();
std::cout << "back in main\n";
}
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native. The standard library has
std::stacktracein the header<stacktrace>. This example uses a destructor instead: the destructor ofFrameruns on every return, so the copy of the stack stays correct.
import java.util.stream.Collectors;
public class Main {
static String where() {
return StackWalker.getInstance().walk(frames -> frames
.skip(1) // skip where itself
.map(StackWalker.StackFrame::getMethodName)
.collect(Collectors.joining(" <- ")));
}
static void c() {
System.out.println(" stack: " + where());
}
static void b() {
System.out.println(" call c");
c();
System.out.println(" back in b");
}
static void a() {
System.out.println(" call b");
b();
System.out.println(" back in a");
}
public static void main(String[] args) {
System.out.println("call a");
a();
System.out.println("back in main");
}
}
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native. Each thread has its own JVM stack.
StackWalkergives the frames of the current thread as a stream, from the top frame down. Throwable.getStackTrace()gives the same data for the place where an exception was made.
#include <stdio.h>
/* C has no standard way to read the call stack. The program keeps its own copy:
each function pushes its name on entry and pops it before it returns. */
static const char *names[16];
static int depth = 0;
#define ENTER(name) (names[depth++] = (name))
#define LEAVE() (depth--)
static void where(void) {
printf(" stack:");
for (int i = depth - 1; i >= 0; i--) {
printf(i == depth - 1 ? " %s" : " <- %s", names[i]);
}
printf("\n");
}
static void c(void) {
ENTER("c");
where();
LEAVE();
}
static void b(void) {
ENTER("b");
printf(" call c\n");
c();
printf(" back in b\n");
LEAVE();
}
static void a(void) {
ENTER("a");
printf(" call b\n");
b();
printf(" back in a\n");
LEAVE();
}
int main(void) {
ENTER("main");
printf("call a\n");
a();
printf("back in main\n");
LEAVE();
return 0;
}
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native. The compiled program uses the call stack, but the C standard has no function to read it. A debugger such as GDB shows it with the
backtracecommand. - The
namesarray copies the push on call and the pop on return by hand.
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
Demo.main();
static class Demo
{
// The frames of this class on the stack, innermost first, without WhereAmI itself.
[MethodImpl(MethodImplOptions.NoInlining)]
static string WhereAmI() =>
string.Join(" <- ", new StackTrace(1)
.GetFrames()
.Select(DiagnosticMethodInfo.Create)
.Where(m => m?.DeclaringTypeName == "Demo")
.Select(m => m!.Name));
[MethodImpl(MethodImplOptions.NoInlining)]
static void c() => Console.WriteLine(" stack: " + WhereAmI());
[MethodImpl(MethodImplOptions.NoInlining)]
static void b()
{
Console.WriteLine(" call c");
c();
Console.WriteLine(" back in b");
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void a()
{
Console.WriteLine(" call b");
b();
Console.WriteLine(" back in a");
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void main()
{
Console.WriteLine("call a");
a();
Console.WriteLine("back in main");
}
}
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native.
System.Diagnostics.StackTracecaptures the frames of the current thread.new StackTrace(1)skips one frame, the frame ofWhereAmI. - The JIT compiler can inline a small method, and then its frame is not in the trace.
MethodImplOptions.NoInliningkeeps each frame. The methods have lower-case names only so that the output matches the other files.
function where() {
// Error.prototype.stack is not in the standard; Node.js writes " at name (place)".
const names = new Error().stack
.split("\n")
.map((line) => line.trim().split(" ")[1])
.filter((name) => ["a", "b", "c", "main"].includes(name));
return names.join(" <- ");
}
function c() {
console.log(" stack:", where());
}
function b() {
console.log(" call c");
c();
console.log(" back in b");
}
function a() {
console.log(" call b");
b();
console.log(" back in a");
}
function main() {
console.log("call a");
a();
console.log("back in main");
}
main();
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native. The engine keeps the call stack. A program sees it only through the
stackstring of anError, which is not in the standard, so the code keeps only the names it knows. - The text of each line depends on the engine. This example reads the format of Node.js.
function where(): string {
// Error.prototype.stack is not in the standard; Node.js writes " at name (place)".
const known = new Set(["a", "b", "c", "main"]);
const names = (new Error().stack ?? "")
.split("\n")
.map((line) => line.trim().split(" ")[1])
.filter((name): name is string => name !== undefined && known.has(name));
return names.join(" <- ");
}
function c(): void {
console.log(" stack:", where());
}
function b(): void {
console.log(" call c");
c();
console.log(" back in b");
}
function a(): void {
console.log(" call b");
b();
console.log(" back in a");
}
function main(): void {
console.log("call a");
a();
console.log("back in main");
}
main();
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native. TypeScript runs as JavaScript, so it has the same call stack and the same
stackstring. The type ofstackisstring | undefined, so the code gives an empty string when it is missing.
package main
import (
"fmt"
"runtime"
"strings"
)
func where() string {
pc := make([]uintptr, 16)
n := runtime.Callers(2, pc) // skip Callers and where
frames := runtime.CallersFrames(pc[:n])
var names []string
for {
f, more := frames.Next()
if name, ok := strings.CutPrefix(f.Function, "main."); ok {
names = append(names, name)
}
if !more {
break
}
}
return strings.Join(names, " <- ")
}
func c() {
fmt.Println(" stack:", where())
}
func b() {
fmt.Println(" call c")
c()
fmt.Println(" back in b")
}
func a() {
fmt.Println(" call b")
b()
fmt.Println(" back in a")
}
func main() {
fmt.Println("call a")
a()
fmt.Println("back in main")
}
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native. Each goroutine has its own stack.
runtime.Callersrecords the program counters on it, andruntime.CallersFramesturns them into function names. - The compiler can inline
a,bandc, butCallersFramesaccounts for inlined functions, so the names are all there.
use std::backtrace::Backtrace;
/// The names of the functions of this program on the stack, innermost first.
#[inline(never)]
fn where_am_i() -> String {
let trace = Backtrace::force_capture(); // ignores RUST_BACKTRACE
let names: Vec<String> = trace
.to_string()
.lines()
.filter_map(|line| line.trim().split_once(": ").map(|(_, name)| name.to_string()))
.filter_map(|name| name.strip_prefix("main::").map(str::to_string))
.filter(|name| name != "where_am_i")
.collect();
names.join(" <- ")
}
#[inline(never)]
fn c() {
println!(" stack: {}", where_am_i());
}
#[inline(never)]
fn b() {
println!(" call c");
c();
println!(" back in b");
}
#[inline(never)]
fn a() {
println!(" call b");
b();
println!(" back in a");
}
fn main() {
println!("call a");
a();
println!("back in main");
}
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native.
Backtrace::force_capturerecords the stack of the current thread. The text of a backtrace is for people, and its format can change, so the code keeps only the names of this program. #[inline(never)]keeps the compiler from inlining the functions, so each one has its own frame.
where() {
# FUNCNAME holds the functions on the call stack, innermost first; skip where.
local names=("${FUNCNAME[@]:1}")
local IFS=,
echo "${names[*]}" | sed 's/,/ <- /g'
}
c() {
echo " stack: $(where)"
}
b() {
echo " call c"
c
echo " back in b"
}
a() {
echo " call b"
b
echo " back in a"
}
echo "call a"
a
echo "back in main"
call a
call b
call c
stack: c <- b <- a <- main
back in b
back in a
back in main
- Verdict: native. Bash keeps the names of the active functions in the
FUNCNAMEarray. The last element ismain, the code of the script outside any function. - The
callerbuiltin shows the call stack from the same data.
Variations and related ideas
- Frames on the heap. The stack is a model, and a runtime can store frames in other places. The JVM specification says that "Because the Java Virtual Machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated"3.
- Generators and coroutines. A frame can leave the stack and come back. MDN says that "When a frame is popped, it's not necessarily gone forever, because sometimes we need to come back to it", as for a generator function2.
- Tail calls. "Tail calls can be implemented without adding a new stack frame to the call stack"13. A language with tail-call elimination can run a tail-recursive loop in a fixed amount of stack.
- More than one stack. A thread usually has one call stack, but "additional stacks may be created for signal handling or cooperative multitasking"1.
Pitfalls
- Missing frames in a trace. An optimizing compiler can inline a function, so its frame is not on the stack. The .NET documentation says that "StackTrace might not report as many method calls as expected, due to code transformations that occur during optimization"14. Tail-call elimination also removes frames13. Read a trace from an optimized build with care.
- A trace format is not an interface. Do not parse a stack trace in program logic. MDN warns: "You cannot rely on the precise content of the stack string due to implementation inconsistencies"7. For Rust, "no guarantees are provided about the exact accuracy of a backtrace"15.
- Frames kept alive. In Python, a frame object keeps its locals alive. "Keeping references to frame objects, as found in the first element of the frame records these functions return, can cause your program to create reference cycles"6.
- Deep recursion. Each active call uses space on the stack, so a deep recursion can use all of it. See stack overflow.
Cost
A call and a return cost little, because they only move the top of the stack. For local data, Wikipedia says that to move the top of the stack "is very fast when compared to dynamic memory allocation, which uses the heap space"1. To read the stack is slower. Rust says that "Capturing a backtrace can be a quite expensive runtime operation"15, and for this reason Backtrace::capture does nothing unless an environment variable turns it on15. Capture a trace when an error happens, not in a loop that runs often.
History
Stacks "entered the computer science literature in 1946", when Alan Turing used the words bury and unbury for the call of a subroutine and the return from it16. Klaus Samelson and Friedrich L. Bauer "proposed the idea of a stack called Operationskeller" in 1955, and filed a patent in 195716.
References
- Call stack, Wikipedia, Introduction; Description; Unwinding; Inspection
- JavaScript execution model, MDN Web Docs, Stack and execution contexts
- The Structure of the Java Virtual Machine, Java Virtual Machine Specification, Java SE 21, 2.5.2 Java Virtual Machine Stacks; 2.6 Frames
- 5.1 Designing Register Machines, Structure and Interpretation of Computer Programs, 5.1.4 Using a Stack to Implement Recursion
- Backtraces, Debugging with GDB, Whole page
- inspect, Python 3.14 documentation, The interpreter stack
- Error.prototype.stack, MDN Web Docs, Introduction; Description
- StackWalker, Java SE 21 API, Class description
- runtime, Go standard library, func Callers; func CallersFrames
- std::basic_stacktrace, C++ reference, cppreference.com, Introduction
- Bash Variables, Bash Reference Manual, FUNCNAME
- Get-PSCallStack, PowerShell documentation, Description
- Tail call, Wikipedia, Introduction
- StackTrace Class, .NET API reference, Remarks
- Module std::backtrace, Rust standard library, Accuracy; Environment Variables
- Stack (abstract data type), Wikipedia, History
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag PY0RER Edit this page History Report an error Markdown