Sub topic 13
Recognizing out-of-memory symptoms
This chapter assumes you can read the build report, use the freeRam() helper, and know the SRAM layout of static data, heap and stack. All numbers refer to an AVR board such as the Uno, which has 2048 bytes of SRAM.
An AVR has no memory protection and no operating system. When SRAM runs out, nothing raises an error. The stack and heap overwrite each other or your globals, and the sketch keeps running on corrupted data. The symptoms look like unrelated bugs, so you need to recognize them and then measure.
Why running out of SRAM fails silently
SRAM is laid out from low to high addresses as static data (.data and .bss), then the heap, which grows upward. The stack starts at the top of SRAM and grows downward. Free memory is the gap between the heap top and the stack pointer.
If that gap shrinks to zero, one of two things happens:
- The stack grows into the heap. A deep call or a large local array overwrites heap blocks, such as the contents of a
String. - The heap grows into the stack.
malloc()andStringdo not check the stack pointer. They hand out memory that the stack is about to use or already uses.
Either way, the writer corrupts the other region. The damage appears later, in code that has nothing to do with the cause.
Common symptoms
No single symptom proves a memory problem, but these patterns together point to one.
| Symptom | Likely mechanism |
|---|---|
| Sketch resets at random, or restarts in a loop | A corrupted return address sends execution to a bad location, or the watchdog fires after a hang |
| Serial output turns into garbage or odd characters mid-run | A `String` or char buffer in the heap was overwritten |
| A variable holds a value you never assigned | The stack or heap wrote over a global |
| Sketch works until you add one more `Serial.print()` | The new string literal pushed static data up and shrank the free gap |
| Behavior changes after you only rename or reorder things | Memory layout shifted, so a latent overwrite now hits different data |
| Sketch runs for hours, then fails | Slow heap leak or fragmentation from repeated `String` use |
| Works at startup, fails when a feature activates | One code path calls a deep function or allocates a large local array |
| Sensor readings or `millis()` math become wrong | A corrupted global that holds timing or calibration data |
Two properties help you separate memory faults from ordinary bugs:
- Sensitivity to unrelated changes. Ordinary logic bugs do not depend on adding a print statement elsewhere. Memory corruption often does.
- Time dependence. A bug that appears only after a long run, or only on some input, suggests growth or fragmentation rather than a wrong formula.
Slow failure versus sudden failure
Heap fragmentation fails slowly. Free memory looks adequate, but no contiguous block is large enough, so an allocation fails or returns NULL. A String that cannot grow silently becomes empty. The symptom is missing text, not a crash.
Stack overflow fails suddenly. A function call enters a deep path, the stack pointer crosses into data, and the sketch goes wrong or resets within a fraction of a second.
Check the cheap evidence first
Before adding any code, check the build output.
- Look at the line "Global variables use N bytes ... leaving M bytes for local variables." The remaining M bytes are shared by the heap and the stack. If M is under about 300 on a 2 KB board, you have little room.
- Look for the warning "Low memory available, stability problems may occur." The IDE prints it when little SRAM is left after static data. Treat it as a strong hint, not a proof.
- Remember that the report counts only static data. It cannot see heap growth or stack depth, so a clean report does not rule out an overflow.
Measure the minimum free RAM
One reading of freeRam() at startup says little. What matters is the lowest value the sketch ever reaches. Track it in loop() and also at the deepest points of your call tree.
extern int __heap_start;
extern int *__brkval;
int minFree = 32767;
int freeRam() {
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
void trackRam() {
int f = freeRam();
if (f < minFree) {
minFree = f;
}
}
void setup() {
Serial.begin(9600);
}
void loop() {
trackRam();
Serial.print(F("Min free RAM: "));
Serial.println(minFree);
delay(1000);
}Call trackRam() from inside the functions that you suspect use the most stack, because loop() runs at a shallow stack depth and will not see the peak. If minFree drops below roughly 100 bytes, you are close to a collision. If it goes negative, the regions have already overlapped.
Detect stack growth with a painted pattern
freeRam() samples a single instant. To find the deepest stack use over a whole run, fill the free gap with a known byte at startup. Later, count how much of it is still untouched. Any byte that changed was reached by the stack or the heap.
extern uint8_t __heap_start;
extern uint8_t *__brkval;
const uint8_t PAINT = 0xAA;
uint8_t *gapStart() {
return (__brkval == 0) ? &__heap_start : __brkval;
}
void paintFreeRam() {
uint8_t marker;
uint8_t *end = &marker - 16; // stay clear of this function's own frame
for (uint8_t *p = gapStart(); p < end; p++) {
*p = PAINT;
}
}
int untouchedBytes() {
uint8_t marker;
uint8_t *end = ▮
int count = 0;
for (volatile uint8_t *p = gapStart(); p < end && *p == PAINT; p++) {
count++;
}
return count;
}
void setup() {
Serial.begin(9600);
paintFreeRam();
}
void loop() {
Serial.print(F("Never-touched bytes: "));
Serial.println(untouchedBytes());
delay(1000);
}This works as a high-water mark because the stack grows down into the painted area from above. The count of untouched bytes counts up from the heap top, so it shows how close the stack has come to the heap. A value that keeps shrinking as you exercise the sketch shows your real worst case. Run every feature of the sketch before you trust the number.
Limits of this method:
- Paint is written once. If the heap grows after painting, the heap overwrites paint, and the count shrinks for that reason too. Allocate any long-lived heap objects before calling
paintFreeRam(), or avoid the heap, as earlier chapters recommend. - A value of
0xAAmay occur naturally in data. That is rare in the gap, but it can make the count read slightly high.
Isolate the cause by elimination
When the sketch misbehaves and the numbers are unclear, narrow it down.
- Reproduce reliably. Find the input or time at which it fails. A repeatable fault is much easier to bisect.
- Remove memory consumers one at a time. Comment out large
Stringoperations, large arrays, or library features. If the fault disappears, you found a consumer, not necessarily the cause. - Shrink something deliberately. Cut a global buffer from 200 to 100 bytes. If the symptom changes or vanishes, memory pressure is involved.
- Wrap literals in
F(). If wrapping debug strings inF()removes a crash, the sketch was short of SRAM. - Test on a larger board. If the same code runs correctly on a Mega with 8 KB of SRAM, the logic is probably sound and the problem is memory.
Match the symptom to the fix
| What you found | What to do |
|---|---|
| Static data leaves little room | Move literals to flash with `F()` and tables with `PROGMEM`, and shrink data types |
| `minFree` falls only inside one function | Reduce local arrays there, avoid recursion, or make the buffer a smaller static |
| Free RAM falls slowly over time | Look for a leak or repeated `String` concatenation, and use `reserve()` or fixed char buffers |
| Free RAM looks fine but strings go empty | Suspect fragmentation and replace `String` with `snprintf()` into a fixed buffer |
| Resets with no pattern | Check free RAM first, then power supply and watchdog settings |
Not every reset is a memory fault. A weak power supply, a brownout from a motor or servo, and a watchdog timeout can all cause the same restart. Measure free RAM before you decide.
Practical habits
- Keep at least 10 to 15 percent of SRAM free as a margin. On a 2 KB board, that is about 200 to 300 bytes.
- Print
minFreeduring development, and remove or disable it when you ship. - Recheck free RAM every time you add a library. Libraries often allocate buffers at startup that do not appear in your own code.
- Prefer decisions made at compile time, such as fixed buffers and constant sizes, over decisions made at run time, such as
malloc()andStringgrowth.
Exercise
Your sketch reports "leaving 780 bytes for local variables" at compile time, yet it resets after about ten minutes of running. It builds strings with repeated String concatenation. Name two measurements you would take, and what result from each would support a memory fault.
Show answer
First, track the minimum free RAM with freeRam() over the whole run. A value that keeps falling, or that nears zero before the reset, supports a leak or heap growth. Second, check whether text from the String objects goes empty or garbled before the reset. That supports fragmentation or a failed allocation, even if total free RAM looks adequate. A good follow-up is to replace the String use with snprintf() into a fixed char buffer and see whether the resets stop. The compile-time figure of 780 bytes does not count heap use, so it cannot rule out the problem.
Exercise
A sketch works. You add one Serial.println("Starting calibration") to setup() and it now prints garbage and resets. Explain the likely cause and give two fixes.
Show answer
A plain string literal is copied into SRAM on AVR boards. The new literal uses extra static data, which reduces the gap left for the heap and stack, and the sketch was already close to the limit. Fix one: write Serial.println(F("Starting calibration")) so the text stays in flash. Fix two: reduce other SRAM use, for example by moving other literals to F(), moving constant tables to PROGMEM, or shrinking a buffer, then confirm with freeRam() that the margin has grown.