Definition
A stack overflow is the error in which a thread’s stack needs more memory than the region reserved for it. The stack is the memory where a thread keeps one frame for each function call still in progress; a frame holds the call’s local variables, saved register values and return address. Each call adds a frame and each return removes it. When the frames present at one moment exceed the region, the newest frame extends into other memory, unless hardware stops the access with a fault.
The idea
A thread on a microcontroller §6.1 runs with a stack of 1 KiB, where a desktop thread usually has 1 MiB or more. Most of the time the thread uses half of its stack. Once a week, an error is logged while a long message is being parsed, at the moment an interrupt §6.11 arrives. That combination needs more than 1 KiB, and the frame at the deepest point overwrites the memory next to the stack: perhaps another thread’s stack, perhaps a variable. Nothing fails at that moment. The damage shows up later, somewhere else.
A pile of plates under a shelf is a fair picture. Each call puts a plate on the pile and each return takes the top plate off. What matters is the greatest height the pile ever reaches, not how many plates pass through it in a day: a thousand calls made one after another never pile up. The picture stops being accurate in one respect. A pile that reaches the shelf stops visibly. A stack that reaches the end of its region keeps going into the neighboring memory, unless something has been placed there to stop it.
How it works
Three parts are involved.
Stack region. A fixed range of addresses reserved for one thread when the thread is created. On most processors, including Arm and x86, the stack grows toward lower addresses: it starts at the top of the region and each new frame lies below the previous one.
Stack pointer. A processor register that holds the address of the current end of the stack. A function reserves its frame by moving the stack pointer down by the frame size, and releases the frame by moving it back.
Frame. The bytes one call occupies: local variables the compiler could not keep in registers, copies of registers the function must restore before it returns, the return address (the place where execution continues after the call), arguments that do not fit in registers, and padding that keeps the stack pointer aligned. The compiler decides the frame size, so the size depends on the compiler, its version and its optimization options, not only on the source code.
The stack depth at a moment is the sum of the frames present at that moment. Three things decide the greatest depth.
The deepest call path. In the call graph, each function points to every function it can call. A path runs from the thread’s entry function, where the thread starts, down to a function that calls nothing. The demand of a path is the sum of its frame sizes, and the deepest path is the one with the largest sum. It need not be the path with the most calls: one function with a large local array §14.5 can outweigh five small ones. Calls made one after another do not add up, because each frame is gone before the next call starts.
Recursion. A function that calls itself, directly or through other functions, adds its frames again at every level. The depth is bounded only if the number of levels is bounded, and that number is often set by the input, such as how deeply the elements of a received message are nested.
Interrupts and exceptions. An interrupt is a signal, usually from a hardware device, that makes the processor suspend the running code and run a handler; an exception, such as a fault, works the same way. The processor saves the interrupted state, and the handler needs frames of its own. Whether these land on the interrupted thread’s stack depends on the processor and the operating system. If handlers of higher priority can interrupt handlers §6.12 of lower priority, which is called nesting, the worst case puts one handler of each priority level on top of the deepest thread path.
Arm Cortex-M processors, common in microcontrollers, split the interrupt demand between two stacks. On an interrupt, the processor saves 8 registers, 32 bytes, onto the stack in use, which under a typical real-time operating system is the interrupted thread’s stack; with floating-point registers to save as well, it saves 104 bytes, and it may add 4 bytes of padding to keep the stack aligned to 8 bytes. The handler then runs on a separate main stack, where nested handlers also go. So every thread stack must leave room for one saved state, and the main stack must hold the deepest nesting of handlers.
Two methods find the depth.
Stack painting. When the thread is created, fill its whole stack region with a known byte pattern, such as
0xAAin every byte. Run the program. Then scan the region from the far end, the end toward which the stack grows, up to the first byte that no longer holds the pattern. The bytes beyond it were never written. The written part is the greatest depth reached so far, called the high-water mark. Many real-time operating systems offer this as a report of stack usage.Static analysis §3.1, which examines the program without running it. Take the frame size of every function from the compiler: GCC §12.17 (GNU Compiler Collection; GNU stands for GNU’s Not Unix) writes the sizes to a file ending in
.suwhen given the option-fstack-usage. Build the call graph from the source code or from the compiled program, and compute the deepest path from each thread’s entry function, counting each recursion up to its stated largest number of levels. Add the demand of the interrupt handlers. The result is an upper bound: no run can go deeper, provided the call graph contains every call that can happen.
The static analysis must settle four hard cases.
Indirect calls, made through a function pointer, a variable that holds the address of a function. The analysis must know every function the pointer can hold and take the deepest of them. One missing target makes the bound wrong.
Recursion, a cycle in the call graph. A cycle has no deepest path until someone states the largest number of levels; the analysis then counts the cycle that many times.
Stack space sized while running, by a variable-length array or the function
alloca. GCC marks such functionsdynamicin the.sufile, and the analysis needs a stated largest size.Code without frame information, such as hand-written assembly language and precompiled libraries, whose frames must be found by reading their machine code.
Detecting an overflow at the moment it happens needs something at the end of the region.
A guard region is a strip of memory at the end of the stack that no code may touch. With an MPU §6.8 (memory protection unit), hardware that checks every memory access against a table of address ranges, the strip is marked as allowing no access. The first write into it causes a fault, and a fault handler §6.15, the routine the processor runs on such an error, can stop the thread or reset the device. Desktop operating systems place a guard page below each thread’s stack for the same purpose: a page, the unit of usually 4 KiB in which the operating system manages memory, that the program may not access.
A stack limit register, present on many processors of the Armv8-M architecture such as the Cortex-M33, holds the lowest address the stack pointer may reach, and the processor raises a fault when the stack pointer would go below it.
A canary is a known value written just beyond the end of the stack and checked from time to time, for example at every switch from one thread to another. A changed canary shows that an overflow has already happened; it prevents nothing.
Worked example
A thread has a stack of 1024 bytes. The compiler reports these frame sizes, in bytes: main_loop 48, handle_msg 160, parse 320, checksum 64, send 200, log_error 96 and format 400. The calls are as follows: main_loop calls handle_msg or log_error; handle_msg calls parse and, after parse has returned, send; parse calls checksum; log_error calls format. The three paths are:
main_loop,handle_msg,parse,checksum: bytes;main_loop,handle_msg,send: bytes;main_loop,log_error,format: bytes.
The deepest path needs 592 bytes, and it does not contain the largest frame, the 400 bytes of format. The sum of all seven frames, bytes, is not the demand, because send runs only after parse has returned, and the two branches of main_loop are never active together.
Suppose this processor runs interrupt handlers on the interrupted stack and has two interrupt priority levels. The low-priority handler needs 152 bytes, saved state included. The high-priority handler needs 232 bytes and can interrupt the low-priority one. Neither can interrupt itself. The worst nesting adds bytes, so the peak is bytes, which leaves bytes to spare.
Now a new message format lets an element contain another element, and parse calls itself for the inner one. With one level of nesting, the deepest path is main_loop, handle_msg, parse, parse, checksum: bytes. With both interrupts on top, the peak is bytes, which exceeds the 1024-byte stack by bytes. The overflow happens only when a nested message is being checked while both interrupts are active. With levels of nesting the thread path alone needs bytes, so from on the stack overflows even without interrupts: bytes.
A test that sends only messages without nesting, and in which no interrupt happens to arrive at the deepest point, reports a high-water mark of 592 bytes. That number is true for the test, and it is bytes short of the worst case with one level of nesting.
Frame sizes come from the compiled code, not from the declarations. GCC 13, compiling for x86-64 with the optimization option -O2, reported a function big whose only local variable is a 300-byte array with the line s.c:1:6:big 336 static in its .su file. The line gives the file, line and column, the function name, a frame of 336 bytes, and the word static, meaning that the size is fixed at compile time. The 36 bytes beyond the array are space the compiler added, such as alignment §4.22 padding and saved values.
Stated precisely
Let be the call graph of one thread: its nodes are functions, and it has an edge from to when can call . Let be the number of bytes that the compiled function adds to the stack. If has no cycles, the greatest demand of a call of , counting the calls it makes, is with the maximum taken as 0 when calls nothing. The thread needs bytes, where is its entry function.
Let the interrupt handlers that run on this stack have priority levels, and let be the set of handlers at level . Let be the number of bytes the processor saves on entry to a handler, alignment padding included. If a handler can be interrupted only by a handler of a strictly higher level, the worst nesting holds at most one handler of each level, and the interrupt demand is A stack of bytes cannot overflow if . On a processor that runs handlers on a separate stack, as Cortex-M does, the thread’s stack needs bytes instead, and the same reasoning bounds the separate stack.
The bound holds under five assumptions.
Complete call graph. contains every call that can happen, including indirect calls through function pointers, calls into libraries and calls from assembly code.
Frame sizes of the running build. Each comes from the same build, with the same compiler, version and options, as the program that runs.
No unbounded stack allocation. Every variable-length array and every call of
allocahas a known largest size, included in its frame.Bounded recursion. Each cycle in has a stated largest number of levels and is counted that many times.
Known nesting. The priority levels, and the rule that only a strictly higher level can interrupt, hold as stated.
Under these assumptions is an upper bound on the stack depth. A measured high-water mark is a lower bound: it is the greatest depth that the measured runs actually reached. The true worst case therefore satisfies .
Limits and common mistakes
A high-water mark is not a bound. It covers only the paths, inputs and interrupt timings that occurred during the runs. It can even miss part of what did occur: a function that reserves a large array but writes only part of it can leave the deepest bytes holding the pattern, and a byte written with a value equal to the pattern looks unwritten.
A static bound can be too large, or wrong. It counts paths that may never run together, so it is usually larger than any measurement; that is the price of covering every path. It is wrong, meaning too small, if the call graph misses a target of an indirect call or if the analyzed build differs from the one that runs.
A guard catches only what touches it. A function whose frame is larger than the guard region can move the stack pointer past the whole guard and then write beyond it without ever touching it. This is known as a stack clash. GCC’s option -fstack-clash-protection makes a function with a large frame touch the stack at regular steps while reserving the frame, so that the guard is always hit.
A stack overflow is not a buffer overflow §4.4. A buffer overflow writes past the end of one array, and the array may sit on a stack with room to spare. The compiler’s stack protector (GCC’s option -fstack-protector) places a canary next to the return address in each frame and checks it before the function returns. It detects that buffer overflow inside one frame, not the stack running out of room.
Optimization changes frame sizes. Inlining, in which the compiler copies a called function into its caller, merges two frames into one, and the merged frame can be larger than either. A build without optimization often uses much more stack than an optimized one. Analyze and measure the build that runs.
Recursion driven by input is a known weakness. A parser that recurses once for each level of nesting in its input lets the sender choose the stack depth. The CWE (Common Weakness Enumeration), a public catalog of software weaknesses, lists this as CWE-674, uncontrolled recursion. The repair is a limit on the depth, checked before each recursive call, or a loop with an explicit work stack of fixed capacity.
An interpreter §2.13 has two stacks. A VM §2.3 (virtual machine), a computer defined in software, keeps the stack of the guest program it runs in memory of its own. A bound on that guest stack §2.25 says nothing about the native stack of the thread that runs the interpreter and the routines it calls.
Questions answered
Which call path, recursion, or interrupt nesting produces the deepest stack?
The deepest stack comes from the combination that puts the most bytes on the stack at one moment: the call path from the thread’s entry function whose frames add up to the most bytes, with each recursive cycle repeated as many times as it can repeat, plus the deepest chain of nested interrupt handlers that can run on the same stack at that moment. A frame is the memory one function call occupies on the stack, and its size comes from the compiled code, not from counting calls or local variables in the source. The path with the most calls, or with the largest single frame, is not necessarily the deepest.
Find the combination by static analysis: take each function’s frame size from the compiler (for GCC, the GNU Compiler Collection, the option -fstack-usage), walk the call graph to find the path with the largest sum, include every possible target of indirect calls, require a stated largest depth for every recursion, and add one handler for each interrupt priority level that can nest, with the processor’s saved state for each. Confirm with stack painting, which fills the stack with a known pattern and reports the deepest byte overwritten. That high-water mark is only a lower bound, because it shows only what the test runs reached.
Related entries: VM stack (§2.25), Buffer overflow (§4.4), Static, stack, and heap storage (§4.11), Memory protection unit (MPU) (§6.8), Exception and fault handler (§6.15), Static analysis (§3.1).