Sub topic 7
Measuring free RAM while the sketch runs
The compiler's memory report tells you how much SRAM your global variables use. It cannot tell you how much memory is left while the sketch runs, because the heap and stack change size at run time. This chapter shows how to measure free SRAM from inside the sketch, how the measurement works, and where it can mislead you.
Prerequisites
This chapter assumes you can:
- Write and upload a basic Arduino sketch and use the Serial Monitor.
- Read C/C++ variables, arrays, functions and pointers.
- Describe the SRAM layout of an AVR board: static data, heap and stack. The example numbers below use an Uno (ATmega328P, 2048 bytes of SRAM).
Why a run-time measurement is needed
The build report gives a fixed number: the bytes used by global and static variables. The report says "leaving N bytes for local variables". That number is only an estimate, because it ignores two things that change while the sketch runs:
- The heap grows when code calls
malloc(),new, or uses theStringclass. - The stack grows when functions are called and shrinks when they return.
Free RAM is the gap between these two. If the gap reaches zero, the stack and heap overwrite each other or your globals, and the sketch misbehaves in ways that are hard to trace. A run-time check lets you see the gap before that happens.
The memory map
On AVR, SRAM is laid out from low addresses to high addresses like this:
- Static data (
.dataand.bss): global and static variables. This region has a fixed size. - The heap: starts just above static data and grows upward.
- The free gap.
- The stack: starts at the top of SRAM (
RAMEND) and grows downward.
The free-RAM helper measures the gap labeled "Free RAM" at the moment you call it.
The freeRam() helper
This helper is the standard AVR technique:
extern int __heap_start;
extern int *__brkval;
int freeRam() {
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
void setup() {
Serial.begin(9600);
Serial.print(F("Free RAM: "));
Serial.println(freeRam());
}
void loop() {
}On an Uno, the output is a number a little under 2048 minus your global variables. Compile and run it first with no other code, so you have a baseline.
How it works
__heap_startis a symbol the linker provides. It is the address where the heap begins, right after static data.__brkvalis a pointer maintained bymalloc(). It marks the current top of the heap. Before the first allocation it is0, so the code falls back to__heap_start.vis a local variable. Local variables live on the stack, so&vis an address close to the current stack pointer.- Subtracting the heap top from the stack address gives the number of bytes between them.
The extern declarations do not create variables. They tell the compiler that these symbols are defined elsewhere (in the linker script and in avr-libc).
What the number means
The return value is the free space at the moment of the call. It is not a minimum or a guarantee. Two details matter:
- The value is measured inside
freeRam(), so the function's own stack frame is already counted as used. The error is a few bytes. - If the sketch later calls a deeper chain of functions, the stack will use more of the gap than
freeRam()showed. Free RAM measured insetup()is usually much higher than it is in the deepest function.
The return type is int, which is fine on AVR because addresses are 16 bits. On boards with 32-bit addresses, this casting approach does not work. See the section on other boards below.
Using the helper effectively
A single reading at startup is of limited use. Measure at the points where memory use peaks.
Log at key points
Print the value before and after operations you suspect:
extern int __heap_start;
extern int *__brkval;
int freeRam() {
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
String message;
void setup() {
Serial.begin(9600);
Serial.print(F("Start: "));
Serial.println(freeRam());
message.reserve(40);
Serial.print(F("After reserve: "));
Serial.println(freeRam());
message = "Reading: ";
message += 512;
Serial.print(F("After build: "));
Serial.println(freeRam());
}
void loop() {
}The "After reserve" value drops by about 41 bytes (40 characters plus the terminating null) plus a few bytes of allocator overhead. The "After build" value stays the same, because reserve() already allocated the storage. Without reserve(), the String would allocate and reallocate as it grows, and the numbers would show it.
Track the lowest value
The most useful figure is the lowest free RAM the sketch ever reaches. You can record it in a global variable:
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 sample() {
int f = freeRam();
if (f < minFree) {
minFree = f;
}
}
void setup() {
Serial.begin(9600);
}
void loop() {
sample();
Serial.print(F("Lowest free RAM so far: "));
Serial.println(minFree);
delay(1000);
}Call sample() from inside deeply nested functions and inside loops that build strings. A call placed only in loop() misses the stack peak that happens inside called functions.
Keep the diagnostics cheap
The diagnostic code itself uses memory. Note the use of F() in the prints above: without it, each message literal would take SRAM bytes and distort the reading you are trying to take. A global minFree costs 2 bytes. That is a fair price for the information.
Limits of the measurement
| Situation | What the helper reports | Why |
|---|---|---|
| Fragmented heap | A large number even though large allocations fail | Free blocks inside the heap are not counted. Only the gap above the heap top is. |
| Deep call chain later | A number that is too optimistic | The stack has not grown yet at the time of the call. |
| Interrupt handlers | A number that ignores their stack use | Interrupts push registers onto the same stack when they fire, at unpredictable times. |
| Large local arrays | A drop only inside the function that declares them | The array is allocated on the stack when the function is entered. |
The fragmentation row is the one that most often surprises people. The helper measures the space between the heap top and the stack, but a freed block lower in the heap sits on a free list that malloc() can reuse. Those bytes are free, but the helper does not count them. A sketch with many freed small strings can show a healthy gap and still fail to allocate one larger block, because the free pieces are split into small fragments. Treat the helper as a measure of the unclaimed gap, not as proof that every allocation will succeed.
Interpreting the numbers
As a working rule on a 2 KB board, treat these ranges as guidance, not as exact limits:
- Several hundred bytes free at the lowest point: comfortable.
- Under about 200 bytes free at the lowest point: risky. A new feature or a longer string could tip it over.
- Under about 50 bytes free: critical. Expect random behavior.
These thresholds come from experience, not from a specification. They depend on how deep your calls go and how much your interrupt handlers use.
Other boards
The helper above relies on AVR-specific symbols (__heap_start, __brkval) from avr-libc. It will not compile on ARM-based boards. Those boards expose different symbols and often provide a library function or a sbrk()-based method. Check your board package documentation for the right approach. The idea is the same: find the heap top, find the stack pointer, and subtract.
Boards with more SRAM make the measurement less urgent, but the same method is still useful for catching leaks. If the minimum free value keeps shrinking over hours of running, the sketch leaks memory or fragments its heap.
A practical workflow
- Compile and read the build report for the static data figure.
- Add
freeRam()and print a baseline insetup(). - Add
sample()calls in the deepest and most allocation-heavy functions. - Run the sketch through all its features, then read
minFree. - If the minimum is low, move literals to
F(), tables toPROGMEM, and replaceStringwith fixed buffers, then measure again.
Measuring after each change tells you which change helped, and by how much.
Common errors
- Printing the free RAM with a plain string literal such as
Serial.println("Free RAM: "). The literal uses SRAM and shifts the result. - Measuring only once in
setup()and concluding there is plenty of memory. - Copying the helper onto a non-AVR board and getting a link or compile error.
- Treating a large free-RAM number as proof that
malloc()orStringoperations will succeed on a fragmented heap. - Forgetting that
intis 16 bits on AVR. The helper's casts are valid there, and not elsewhere.
Exercise
A sketch prints "Free RAM: 1100" in setup() on an Uno, but it resets at random times when a function parseCommand() runs, which declares a 600-byte local array and calls two other functions. Explain what the reading missed, and describe where to place sample() calls to confirm the cause.
Show answer
The reading in setup() was taken before the stack grew. When parseCommand() runs, its 600-byte array is allocated on the stack, and the two nested calls add their own frames, so the gap shrinks well below 1100 and may reach zero, which corrupts memory and causes resets. To confirm, call sample() inside parseCommand() right after entry and inside each of the two functions it calls, then print minFree. Moving the array to a smaller global buffer, or shrinking it, and measuring again should show a higher minimum.
Exercise
Why can freeRam() report 400 bytes while a malloc(300) call still fails?
Show answer
freeRam() measures only the gap between the heap top (__brkval) and the stack. Freed blocks lower in the heap are not counted, and they may be split into pieces smaller than 300 bytes. If malloc() cannot find a single free block of 300 bytes and the gap does not allow growing the heap by 300 bytes plus overhead, the call fails even though the helper shows 400. Part of that 400 is also needed for the stack to grow, so the heap cannot use all of it.