{
  "id": "call-stack",
  "title": "Call Stack",
  "lang": "en",
  "source_lang": "en",
  "summary": "A call stack tracks active function calls, preserving the information needed to manage local execution state and resume callers when functions return.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Function call stack",
    "Execution stack",
    "Control stack",
    "Runtime stack"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/call-stack/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/call-stack/",
      "json": "https://aiwiki.page/zh/call-stack.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A call stack is a runtime data structure that records active invocations of subroutines, such as functions, procedures, and methods. It normally follows the last-in, first-out discipline of a stack: when one function calls another, information about the new invocation is added; when that invocation returns, its information is removed and execution resumes in the caller. Each invocation is represented by a stack frame, also called an activation record. Call stacks support nested calls, local execution state, and recursion, although their physical representation varies across processors, programming languages, and runtime systems."
    },
    {
      "heading": "How a call stack works",
      "text": "Consider three functions in which main calls parse, and parse calls read_token. While read_token is executing, the conceptual call stack is:\n\nTop:     read_token frame   ← currently executing\n         parse frame\nBottom:  main frame\n\nThe parse invocation remains active while it waits for read_token to return. Likewise, main remains active while it waits for parse. A frame therefore represents an invocation that has begun but has not yet completed, not necessarily a function currently executing instructions.\n\nA conventional call proceeds through these steps:\n\n- The caller prepares arguments and preserves any state it must retain.\n- Execution transfers to the called function, or callee.\n- The callee establishes the state needed for its invocation.\n- The callee computes a result, possibly making further calls.\n- On return, the callee’s frame is released, saved state is restored as required, and execution resumes at the caller’s return point.\n\nThese actions implement part of a program’s control flow. Their exact division between caller and callee is determined by the calling convention and generated code; they are not a universal sequence of processor instructions.\n\nThe call stack records the chain of unfinished calls, not a complete execution history. Once an ordinary invocation returns, its frame is generally no longer available as a record of that call."
    },
    {
      "heading": "Stack frames",
      "text": "A stack frame contains, or provides access to, information associated with one invocation. Depending on the implementation, this may include:\n\nComponent | Purpose\nReturn address | Identifies where execution should resume in the caller\nArguments | Supplies input values or references to the callee\nLocal variables | Stores values belonging to the invocation\nSaved registers | Preserves processor state required after the call\nTemporary values | Holds intermediate results and values displaced from registers\nFrame linkage | Helps locate the caller’s frame\nAlignment and bookkeeping data | Satisfies platform and runtime requirements\n\nNot every component must be stored in stack memory. Arguments and return values often travel in processor registers. A return address may initially reside in a link register, while some local variables remain entirely in registers or disappear through optimization.\n\nA compiler commonly emits a function prologue to establish a frame and a function epilogue to dismantle it. Simple functions may need little or no explicit frame setup.\n\nStack pointer and frame pointer\n\nA stack pointer identifies a position near the active end of a machine stack. Allocating or releasing stack space commonly involves adjusting this register. Some platforms use stacks that grow toward lower memory addresses; others use different arrangements. “Top of stack” describes a logical position, not a universally higher address.\n\nA frame pointer, when used, provides a stable reference for locating a function’s saved state and local storage. It can be useful when the stack pointer changes during execution. Compilers may omit it to make another register available, using stack-pointer-relative addressing and unwind metadata instead.\n\nAn application binary interface specifies relevant conventions, including register use, argument placement, stack alignment, and preservation obligations. Consequently, there is no single stack-frame layout shared by all platforms."
    },
    {
      "heading": "Physical and logical representations",
      "text": "A call stack is an execution model, not necessarily one contiguous block of memory.\n\nIn many native programs, each thread has a stack region managed with support from the operating system. Several threads in one process can therefore have different active call chains even while sharing other memory.\n\nRuntime systems can instead use segmented stacks, growable stacks, heap-allocated frames, or combinations of representations. An interpreter may maintain language-level frames separately from the native calls used to implement it. A virtual machine can likewise distinguish virtual frames from underlying machine frames.\n\nOptimization can further separate logical calls from physical frames:\n\n- Inlining incorporates a function’s body into its caller, so no separate machine call or frame may exist.\n- Tail-call optimization can replace the current invocation with another rather than retain both.\n- Register allocation can keep local values outside stack memory.\n- Runtime optimization can reconstruct logical frames when execution must return to a less optimized form.\n\nThus, the number of source-level calls does not always equal the number of physical frames.\n\nCall stack versus other storage\n\nA call stack is distinct from the stack abstract data type, which can also be used for unrelated tasks such as expression parsing or graph traversal.\n\nIt is also distinct from a heap, a storage area used for dynamically managed objects. Stack-associated storage normally follows invocation lifetime, whereas heap objects can outlive the function that created them. This distinction is not an absolute rule about source-language variables: compilers and runtimes may choose different storage locations while preserving program semantics.\n\nIn some virtual machines, an operand stack holds values used by instructions. That stack has a different role from the call stack, even when each call frame contains its own operand stack."
    },
    {
      "heading": "Recursion and space usage",
      "text": "Recursion requires separate execution state for overlapping invocations of the same function. For example:\n\nfactorial(n):\n    if n <= 1:\n        return 1\n    return n * factorial(n - 1)\n\nWhile factorial(4) waits for factorial(3), its invocation must retain enough information to complete the multiplication later. Each deeper call adds another active invocation.\n\nIf the maximum active depth is \\(d\\) and each frame occupies approximately \\(f\\) bytes, stack storage is roughly\n\n\\[S \\approx d f.\\]\n\nReal frame sizes may differ, so a more general expression is\n\n\\[S \\approx \\sum_{i=1}^{d} f_i,\\]\n\nexcluding additional runtime overhead. This makes call depth relevant to an algorithm’s space complexity. A recursive traversal can use storage proportional to the height of a tree, even if its source code contains no explicit stack.\n\nTail calls\n\nA tail call occurs when the caller can return the callee’s result without further computation. With tail-call optimization, the implementation can reuse or replace the caller’s frame rather than preserve it.\n\nThe factorial example above is not directly tail-recursive because multiplication remains after the recursive call returns. An accumulator-based version can place the recursive call in tail position.\n\nWhether tail calls use constant stack space depends on the language’s guarantees and the implementation. A tail-recursive source program does not automatically imply bounded stack usage on every runtime."
    },
    {
      "heading": "Returns, exceptions, and unwinding",
      "text": "An ordinary return removes one invocation at a time. Exception handling may instead transfer control past several callers to a matching handler.\n\nThe process of leaving intervening frames is called stack unwinding. Depending on language semantics, it can involve:\n\n- Locating an applicable handler.\n- Executing cleanup operations.\n- Destroying objects with scope-bound lifetimes.\n- Restoring register and stack state.\n- Transferring control to the handler.\n\nUnwinding is therefore not necessarily equivalent to moving the stack pointer directly to an earlier position. Some nonlocal control-transfer mechanisms bypass cleanup that ordinary language exceptions would perform.\n\nUnwind metadata can describe how to recover saved state even when frames lack an explicit frame-pointer chain."
    },
    {
      "heading": "Debugging and stack traces",
      "text": "A stack trace, also called a backtrace, presents a sequence of active calls. Debuggers, crash reporters, and profiling tools use it to show how execution reached a particular point.\n\nA trace may include function names, source files, line numbers, and instruction addresses. Its accuracy and detail depend on available symbols, debugging information, unwind metadata, and the integrity of program memory.\n\nOptimized execution complicates interpretation. Inlined functions may appear as reconstructed logical frames, while tail-called functions may be absent from the physical stack. Local variables can be unavailable because they were optimized away or because their values no longer occupy recoverable locations.\n\nIn runtimes with garbage collection, stack frames and registers can also hold references that keep objects reachable. The collector must identify those references using mechanisms appropriate to the runtime, such as stack maps or conservative scanning."
    },
    {
      "heading": "Asynchronous execution and coroutines",
      "text": "The synchronous call stack does not necessarily preserve the full causal history of asynchronous execution.\n\nFor example, a function may register a callback and then return. When an event loop later invokes the callback, the original function’s frame is no longer active. The callback belongs to a later execution sequence rather than a continuously nested chain of calls.\n\nA coroutine can suspend and later resume. Implementations preserve suspended state in different ways:\n\n- Stackful coroutines retain a stack or an equivalent representation of nested calls.\n- Stackless coroutines typically store suspension state in objects or transformed state machines rather than retain an entire native call stack.\n\nDevelopment tools may assemble asynchronous stack traces by linking scheduling and suspension information. These traces describe logical causality across separate execution segments, not merely the current physical stack."
    },
    {
      "heading": "Limits and security",
      "text": "A stack overflow occurs when execution exceeds the storage available for its stack. Causes include excessive recursion, very large stack-allocated objects, and unexpectedly deep call chains. A runtime may report an error, raise an exception, or terminate execution, depending on the platform and circumstances.\n\nSystems using virtual memory commonly employ inaccessible guard regions to detect certain attempts to grow beyond stack boundaries. Such protection does not make stack capacity unlimited.\n\nA stack overflow is distinct from a buffer overflow. The former exhausts stack capacity; the latter writes outside a buffer’s bounds. A buffer overflow involving stack-resident data can corrupt local values, saved registers, or return addresses and create a security vulnerability.\n\nDefenses include stack canaries, bounds checking, non-executable memory, address randomization, and protected shadow stacks that maintain a separate record of return addresses. These mechanisms address different failure modes: protecting return addresses does not, by itself, prevent corruption of other data or exhaustion of stack space."
    }
  ],
  "links": [
    "data-structure",
    "subroutine",
    "stack-data-type",
    "recursion",
    "control-flow",
    "compiler",
    "thread-computing",
    "operating-system",
    "interpreter",
    "virtual-machine",
    "algorithm",
    "space-complexity",
    "garbage-collection",
    "asynchronous-programming",
    "event-loop",
    "coroutine",
    "virtual-memory",
    "security-vulnerability"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}