76и. Recursion and the stack on a microcontroller: depth, -fstack-usage and conversion to iteration
In 76а the recursive factorial turned into a loop at -O2, and the stack stayed untouched. One is not always that lucky. Flood-filling a region of an image, walking a tree, parsing nested expressions call themselves several times, and the compiler does not fold such recursion into a loop. The depth then depends on the data — on the shape of the region, on the number of brackets — while a task stack on a microcontroller is measured in hundreds of bytes. Here is how to estimate the depth, how to see the frames and the call graph with gcc's own tools, and how to rewrite recursion onto an own stack with a known limit.
Basis: alg.c with three flood fills and an expression parser built with gcc 12.2.0 on the
computer (stm-sys:1) — the fills on three 32 × 32 fields with a count of the
recursion depth and the peak occupancy of the own stacks, the parser on six
expressions. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2
for Cortex-M4F and Cortex-M0 — frames from -fstack-usage, the call graph from
-fcallgraph-info=su and the number of calls in the machine code. The stack on silicon
was not measured: the bytes are obtained as depth × frame.
Terms used in the documentation
Original Meaning recursion depth recursion depth: how many calls are waiting to return at once call graph, -fcallgraph-info call graph; a gcc option writing it to a .ci file with frames -Wstack-usage=N a gcc warning about a frame larger than N bytes explicit stack explicit stack: an own array instead of the call stack flood fill, scanline fill flood fill, scanline fill recursive descent parser a recursive descent parser nesting limit nesting limit unbounded recursion unbounded recursion: the depth is set by the input data In plain words. Every function call puts a "bookmark" on the stack — where to return and what was in the registers. Recursion puts bookmarks one on top of another until it reaches the bottom, and only then takes them off. If there are a thousand such bookmarks and room for twenty-five, the pile spills onto neighbouring data. An own stack is the same pile, but in a box of known size: when it is full, the program sees it and stops instead of corrupting memory.
76и.1 How much stack a task has and how much a call eats
A task stack in an RTOS is usually 256–1024 bytes, the main stack without an RTOS is whatever
is left of the RAM. Each call takes a frame: saved registers,
the return address, local variables. The frame size is shown by
-fstack-usage — a .su file next to the object file:
| Function | frame M4 | frame M0 |
|---|---|---|
flood_rec |
40 | 40 |
flood_stack |
48 | 48 |
flood_scan |
48 | 56 |
parse_sum |
16 | 24 |
parse_prod |
16 | 16 |
parse_atom |
16 | 16 |
flood_rec takes 40 bytes on M4: the function saves ten registers (r3–r11 and
lr). A 1 KB stack holds 25 such frames — that is the recursion depth
limit if there is nothing else on the stack. And then there are interrupts: an
exception frame with the FPU registers on M4F is 104 bytes (76а), and it lands on
the stack of whichever task was interrupted.
The option -Wstack-usage=N warns about a frame larger than N bytes — at N = 32
gcc named flood_rec (40), flood_stack and flood_scan (48 each). But
it does not see recursion: the warning is about a frame, not about depth.
76и.2 Flood fill by recursion: short and dangerous
Filling a connected region of an image starting from a point is four calls to itself:
int flood_rec(int x, int y, int depth)
{
if (x < 0 || y < 0 || x >= W || y >= H || grid[y][x] != 0)
return 0;
grid[y][x] = 2;
DEPTH_HOOK(depth);
int n = 1;
n += flood_rec(x + 1, y, depth + 1);
n += flood_rec(x - 1, y, depth + 1);
n += flood_rec(x, y + 1, depth + 1);
n += flood_rec(x, y - 1, depth + 1);
return n;
}
A run on a 32 × 32 field from a corner:
| Field | cells filled | recursion depth | frames on the stack at -O2 | stack M4, bytes |
|---|---|---|---|---|
| empty | 1024 | 1024 | 1024 | 40960 |
| snake | 528 | 528 | 528 | 21120 |
| 25 % walls | 746 | 294 | 267 | 10680 |
On an empty field the depth equals the number of cells: the fill goes right to the edge, takes a step down, goes left — and all 1024 calls wait to return at once. 40960 bytes of stack is 20 times all the RAM of a chip with 2 KB. Even on a field with a quarter of walls it is 10680 bytes.
The "frames at -O2" column differs from the depth on the field with walls, and here is
why: the machine code of flood_rec has three bl calls, not four — gcc
turned the last call into a loop that adds into a register. Calls upward
add no frame, so there are 267 real frames, not 294. On the empty
field and the snake the fill never goes up, and there is no difference. You cannot rely on this:
at -O0 there will be no loop, and the worst-case depth is the same.
76и.3 A call graph from gcc
Where the recursion is in a large program is shown by the call graph. The option
-fcallgraph-info=su writes a .ci file with function nodes, their frames and
call edges. For flood_rec it has three edges from the function into itself —
the same three bl. For the expression parser — a ring parse_sum →
parse_prod → parse_atom → parse_sum: recursion through three functions,
which cannot be noticed from the individual frames.
The worst stack is computed like this: the heaviest path through the graph from the task entry point plus the heaviest interrupt handler. A ring in the graph means that there is no worst path until the depth is limited explicitly.
76и.4 An own stack instead of recursion
The same walk, but instead of the call stack — an own array of cell numbers. Its size is fixed, and an overflow is a refusal, not memory corruption:
for (int k = 0; k < 4; k++) {
int nx = cx + DX[k], ny = cy + DY[k];
if (nx < 0 || ny < 0 || nx >= W || ny >= H || grid[ny][nx] != 0)
continue;
if (sp == cap)
return -1;
st[sp++] = (uint16_t)(ny * W + nx);
if (sp > peak)
peak = sp;
}
A cell on the stack is a uint16_t, 2 bytes, against a 40-byte frame. On the empty
field the stack filled up to 962 entries — 1924 bytes, still a lot, but 21 times
less than recursion and, most importantly, predictable: with an array of 64 entries the same
fill honestly returned −1. A refusal can be handled — fill the rest
in a second pass, report an error — a call stack overflow cannot
be handled.
76и.5 Scanline fill: a stack orders of magnitude smaller
A cell-by-cell walk pushes every neighbour onto the stack. Scanline fill fills the whole segment of a row between walls at once, and pushes one seed for each free segment of the rows above and below:
int l = cx, r = cx;
while (l > 0 && grid[cy][l - 1] == 0) l--;
while (r < W - 1 && grid[cy][r + 1] == 0) r++;
for (int i = l; i <= r; i++)
grid[cy][i] = 2;
On the empty field and the snake the scanline fill stack always holds one entry, on the field with a quarter of walls no more than 66, that is 132 bytes. In all three cases as many cells were filled as by recursion: 1024, 528 and 746. The price is code: 264 bytes on M4 against 124 for recursion.
76и.6 Recursive descent with a nesting limit
Parsing expressions with brackets is naturally written with recursion: a sum consists of products, a product of factors, a factor is a number or a bracketed expression. The depth equals the bracket nesting, and that is set by whoever sent the string — a console operator or the remote side. So the depth is limited explicitly:
if (++e->depth > EXPR_MAX_DEPTH) {
e->err = 1; /* слишком глубоко: отказ вместо переполнения стека */
return 0;
}
| Expression | value | error | depth |
|---|---|---|---|
2+3*4 |
14 | 0 | 1 |
(1+2)*(3+4) |
21 | 0 | 2 |
-(-(5)) |
5 | 0 | 5 |
((((((((1)))))))) |
1 | 0 | 9 |
(((((((((((((((((1))))))))))))))))) |
0 | 1 | 16 |
2*(3+ |
6 | 2 | 2 |
Error 1 means the limit of 16 was exceeded, error 2 means a missing closing bracket. The string
with 17 brackets was rejected on entering the 17th level. One bracket level passes
through parse_atom → parse_sum → parse_prod — 48 bytes on M4, and with a
limit of 16 the worst parser stack is known in advance: 16 × 48 = 768 bytes plus
32 bytes of expr_eval. Without a limit a string of a thousand brackets arriving over
the UART would bring the device down.
76и.7 How to convert recursion to iteration
| Kind of recursion | How to remove it |
|---|---|
| tail: the call is the last action | a loop; gcc -O2 often does it itself (76а) |
| one call, work after it | a loop with an accumulator or a pass in reverse order |
| several calls: tree walk, flood fill | an own stack with a size limit |
| a walk of known shape: rows, levels | an algorithm without a stack: scanline fill, level-order walk |
| parsing nested structures | recursion with an explicit depth limit or parsing with an operator stack (76.7) |
The rule for firmware: recursion is allowed only if its depth is limited in the code, not by hope in the data, and the worst stack has been computed: depth × frame plus interrupts.
76и.8 How to check on silicon
The "depth × frame" estimate is an upper bound for one path. The real stack
use is checked by painting: at startup fill the stack with a pattern,
run the worst scenario and find the lowest touched cell — that is how the depth
was measured in QEMU in 76а. In FreeRTOS the same is done by
uxTaskGetStackHighWaterMark. The worst scenario for the fill is an empty field,
for the parser a string with the largest allowed nesting.
76и.9 Pitfalls
The device crashes on an "empty" image. A recursive fill of a uniform region goes to a depth equal to the number of cells: 1024 calls of 40 bytes. An own stack or a scanline fill.
The debug build crashes, the release build does not. At -O2 gcc turned part of the calls into a loop, at -O0 every call is a frame. Compute the worst stack for -O0 or forbid recursion.
The remote side sent a thousand brackets. The parsing depth is set by the input data. A nesting limit in the code — here 16.
-Wstack-usage is silent, but the stack overflows. The warning is about the
size of a single frame, it knows nothing about recursion depth. The call graph
-fcallgraph-info and a search for rings in it.
The own stack overflowed too. The array size was chosen by eye. Compute the worst occupancy on the worst field (here 962 entries) or switch to a scanline fill; on overflow — a refusal with a code, not a write past the edge.
76и.10 Summary
- The
flood_recframe is 40 bytes on M4: a 1 KB stack holds 25 levels. - A recursive fill of an empty 32 × 32 field — depth 1024, 40960 bytes of stack; on a field with 25 % walls — 10680 bytes.
- gcc -O2 turned one of the four calls into a loop: there are three
blin the machine code, 267 frames instead of 294; at -O0 this will not happen. - An own stack on the empty field — 962 entries of 2 bytes, 1924 bytes; with an array of 64 entries — an honest refusal.
- Scanline fill — no more than 66 entries, 132 bytes, on any of the three fields.
- A parser with a nesting limit of 16 — worst stack 768 bytes plus 32, a string with 17 brackets is rejected.
Next: section 76к "Topological sort: module initialisation order and detecting circular dependencies" — how to compute the start-up order of modules from their dependencies and show the developer a cycle by name.