Sub topic 11
Stack usage: local arrays, call depth and recursion
This chapter assumes you can write and upload a sketch, read C/C++ pointers and arrays, and use the Serial Monitor. It also assumes you know the SRAM layout from the earlier chapter: static data at the bottom, the heap above it, and the stack growing down from the top of RAM. The examples target an AVR board such as the Uno, which has 2 KB of SRAM.
What the stack holds
The stack is the region of SRAM that stores the temporary state of running functions. Each time a function is called, the processor pushes a stack frame. A frame typically contains:
- the return address, which is 2 bytes on the Uno's ATmega328P
- the function's local variables, unless the compiler keeps them in registers
- saved registers that the function needs to preserve for its caller
- arguments that did not fit in registers
When the function returns, the frame is released. No cleanup call is needed, and no fragmentation can occur, because frames are always freed in the reverse order they were created.
The stack grows downward, from the highest SRAM address toward the heap. The heap grows upward. Free RAM is the gap between them. If the two meet, one overwrites the other.
The build report from the earlier chapter counts only static data. It cannot see the stack, because stack use depends on which functions are running when the sketch executes. A sketch that reports "Global variables use 900 bytes (43%)" can still crash if its deepest call path needs more than the remaining 1,148 bytes.
Local arrays are the main cost
Scalar locals are cheap. An int costs 2 bytes, and the compiler often keeps small values in registers where they cost nothing. Local arrays are different, because the whole array is allocated in the frame whenever the function runs.
void printReading(int value) {
char text[64];
snprintf(text, sizeof(text), "Value: %d", value);
Serial.println(text);
}
void setup() {
Serial.begin(9600);
printReading(42);
}
void loop() {
}While printReading() runs, 64 bytes of the stack are in use plus the frame overhead. That is about 3% of the Uno's SRAM. This is acceptable once. It becomes a problem when the function is called from deep inside other functions, or when several large buffers exist at the same time.
The cost is easy to miss for three reasons:
- The memory is not counted in the compile-time report.
- It exists only during the call, so a test that runs the function in isolation may pass.
- A buffer declared inside a nested block or a rarely used branch may still reserve its space for the whole function, depending on the compiler's optimization.
Choosing where a buffer lives
You have three places to put a buffer. Each has a different cost profile.
| Location | Lifetime | Counted in build report | Main risk |
|---|---|---|---|
| Local (stack) | Only during the call | No | Collision with the heap at run time |
| Global or `static` | Whole program | Yes | Permanent SRAM use, even when idle |
| Heap (`malloc`, `new`, `String`) | Until freed | No | Fragmentation |
A static local array keeps the function's scope but moves the storage out of the stack:
void printReading(int value) {
static char text[64];
snprintf(text, sizeof(text), "Value: %d", value);
Serial.println(text);
}
void setup() {
Serial.begin(9600);
printReading(42);
}
void loop() {
}Now the 64 bytes appear in the "Global variables" line of the build report, and they are reserved even while the function is not running. This is a trade: you gain predictability, because a compile-time number tells you the cost, and you lose the ability to reuse that memory for other things.
A static buffer also has side effects. The contents persist between calls, and the function is no longer safe to call from both the main code and an interrupt handler. Use it only when you know a single caller uses the buffer at a time.
Sharing is another option. If three functions each need a 64-byte scratch buffer but never run at the same time, one global buffer of 64 bytes can serve all of them. That saves 128 bytes, at the cost of making the code depend on call order.
Call depth
Stack use is the sum of the frames along the deepest call path, not of every function in the sketch. Take this sketch:
void levelC() {
char buf[40];
buf[0] = 'c';
Serial.println(buf[0]);
}
void levelB() {
char buf[40];
buf[0] = 'b';
levelC();
}
void levelA() {
char buf[40];
buf[0] = 'a';
levelB();
}
void setup() {
Serial.begin(9600);
levelA();
}
void loop() {
}When levelC() runs, all three buffers exist at once: 120 bytes of arrays, plus three return addresses and some saved registers. Serial.println() is called from inside levelC(), so its own frames add to the total. Library calls such as Serial.print(), snprintf() with floating-point conversion, and SD or Wire operations can add tens of bytes each.
Two consequences follow:
- Peak usage happens at the bottom of the deepest call chain. To estimate it, add up the frames along that chain and include library calls at the bottom.
- Interrupt service routines (ISRs) push their frame on whatever stack is current. On AVR, the processor also saves registers on entry. An ISR that fires while the main code is deep in a call chain adds its own frame to the peak.
Recursion
A recursive function calls itself, and each call adds a frame. The depth is set by the input, not by the source code, so you cannot tell from reading the sketch how much stack it needs.
unsigned long factorial(unsigned int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
void setup() {
Serial.begin(9600);
Serial.println(factorial(10));
}
void loop() {
}factorial(10) makes 10 nested calls. If each frame uses about 8 bytes, that is roughly 80 bytes, which is fine. But the same function called with a value read from a sensor or a serial command could nest hundreds of calls. At 8 bytes each, 250 calls would use 2,000 bytes, which is the entire SRAM of an Uno.
An iterative version uses one frame regardless of input:
unsigned long factorial(unsigned int n) {
unsigned long result = 1;
for (unsigned int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
void setup() {
Serial.begin(9600);
Serial.println(factorial(10));
}
void loop() {
}Note that an unsigned long overflows past factorial(12). That is a separate bug, but it shows why unchecked input is risky in both versions.
If recursion is the natural fit, for example when walking a tree, apply these rules:
- Enforce a maximum depth and return an error when it is reached.
- Keep the frame small. Pass pointers or indexes instead of copying arrays, and avoid local arrays inside the recursive function.
- Convert the function to a loop with an explicit, fixed-size array used as a stack, so the memory cost appears in the build report.
Passing arrays and objects
Passing an array to a function passes only a pointer (2 bytes on AVR), so it is cheap. Passing a struct or object by value copies the whole thing onto the stack.
struct Sample {
uint16_t values[16];
uint8_t count;
};
uint16_t sumByValue(Sample s) {
uint16_t total = 0;
for (uint8_t i = 0; i < s.count; i++) {
total += s.values[i];
}
return total;
}
uint16_t sumByReference(const Sample &s) {
uint16_t total = 0;
for (uint8_t i = 0; i < s.count; i++) {
total += s.values[i];
}
return total;
}
void setup() {
Serial.begin(9600);
Sample s = {{10, 20, 30}, 3};
Serial.println(sumByValue(s));
Serial.println(sumByReference(s));
}
void loop() {
}sumByValue() copies 33 bytes into its frame, while sumByReference() passes a 2-byte reference. Prefer const & for anything larger than a few bytes. The same applies to returning large objects by value and to String parameters, where passing by value also allocates on the heap.
Measuring the stack
Because the stack's peak is a run-time property, you measure it rather than calculate it. A common technique is stack painting. At startup, fill the free gap with a known pattern. Later, scan from the heap end upward to find how much of the pattern has been overwritten. The overwritten part shows the deepest the stack has reached.
extern uint8_t __heap_start;
extern uint8_t *__brkval;
const uint8_t PATTERN = 0xAA;
void paintStack() {
uint8_t marker;
uint8_t *start = (__brkval == 0) ? &__heap_start : __brkval;
for (uint8_t *p = start; p < &marker - 16; p++) {
*p = PATTERN;
}
}
uint16_t unusedStack() {
uint8_t *start = (__brkval == 0) ? &__heap_start : __brkval;
uint8_t *p = start;
while (*p == PATTERN) {
p++;
}
return p - start;
}
void setup() {
Serial.begin(9600);
paintStack();
Serial.println(unusedStack());
}
void loop() {
}The function leaves a 16-byte margin below the current stack position so that painting does not overwrite the frame of paintStack() itself. Call paintStack() first thing in setup(). After running your sketch through its heaviest code paths, unusedStack() returns the smallest gap observed since painting, which is the safety margin you have left. Call it periodically and print the smallest value seen.
Two limits apply. The pattern may appear in real data (0xAA is a common value, so pick a different byte if your data uses it), and painting finds the high-water mark only for the paths you actually ran. Test the worst case, not the typical case.
Reducing stack use
Apply these in order of payoff:
- Remove large local arrays. Move them to globals, share them, or shrink them.
- Replace recursion with loops, or bound the depth.
- Pass large objects by
constreference. - Flatten call chains that hold large buffers. Do the work that needs the buffer in one function, and release it before calling deeper.
- Keep ISRs short, with no local arrays and no calls to
Serial.print()or other slow library code. - Move constant data to flash with
F()andPROGMEMso that it is not copied onto the stack. Copying a flash string into a local buffer withstrcpy_Pputs its full length back into SRAM for the duration of the call.
Symptoms of a stack overflow
A stack that grows into the heap or into static data produces failures that do not point to the real cause:
- Variables change value although no code writes to them.
- The sketch resets repeatedly, because a corrupted return address sends execution to a random location.
- Output is garbled, or
Stringcontents turn into other characters. - The failure depends on input, such as a long serial line or a particular menu path.
- Adding a harmless
Serial.println()makes the bug disappear or move, because it changes the stack layout.
These match the heap collision symptoms covered in the out-of-memory chapter. Distinguish them by checking the high-water mark from stack painting. If the gap is near zero, the stack is the cause.
Exercise
A function on an Uno declares char line[80]; and calls a helper that declares char tmp[60];, which in turn calls Serial.print(). The sketch reports 1,300 bytes of global variables. Roughly how much SRAM is left for the heap and for everything else at the deepest point, ignoring frame overhead and library frames? Also, name one change that lowers this peak without removing any functionality.
Show answer
The Uno has 2,048 bytes of SRAM. Globals use 1,300, leaving 748. At the deepest point the two arrays use 80 + 60 = 140 bytes of stack, leaving about 608 bytes for the heap and for overhead such as return addresses and the frames inside Serial.print(). One change is to make the two functions share one global 80-byte buffer, which removes 60 bytes from the peak. Another is to finish using line before calling the helper, or to move the helper's buffer to a static variable so its cost is visible in the build report.
Exercise
Why is recursion on a value read from a serial command more dangerous than recursion on a constant such as factorial(10)?
Show answer
The depth of a recursive call chain equals the input, so the stack use is set by whoever supplies the value. With a constant, you can calculate the peak in advance. With external input, a large value can nest enough frames to overrun the stack into the heap, which corrupts data silently. The fix is to cap the depth, or to rewrite the function as a loop.