Sub topic 2
How a sketch uses SRAM: static data, heap and stack
This chapter assumes you can write and upload a basic sketch, read C/C++ variables, arrays, functions and pointers, and use the Serial Monitor. The examples target an AVR board such as the Arduino Uno (ATmega328P), which has 2048 bytes of SRAM.
The SRAM map
SRAM is the only memory your running program can freely read and write for variables. On an Uno it holds 2048 bytes in total. The compiler and the runtime divide that space into regions. Knowing the regions explains most "my sketch behaves strangely" problems on small boards.
From low addresses to high addresses, the SRAM of an AVR looks like this:
- Registers and I/O space. The first 256 or so addresses map CPU registers and peripherals. You do not allocate here, and the 2 KB figure counts only the space above it.
.data. Global and static variables that have a non-zero initial value..bss. Global and static variables that start at zero or have no initializer.- The heap. Memory requested at run time with
malloc(),new, or classes such asString. It grows upward. - Free space between the heap and the stack.
- The stack. Local variables, function arguments and return addresses. It starts at the very top of SRAM (
RAMEND) and grows downward.
The fixed regions never change size while the sketch runs. The heap and stack change constantly. A sketch fails when the heap and stack grow into each other, or when either one grows into the static data.
Static data: `.data` and `.bss`
The compiler knows the size of every global and static variable. It reserves their space before the program starts, and it reports the total in the build output (the next chapter covers that report).
The difference between the two sections matters in one respect. Variables in .data have initial values that must be stored somewhere. On AVR, those values sit in flash and are copied into SRAM by startup code before setup() runs. So an initialized global costs flash and SRAM. Variables in .bss are simply zeroed at startup and cost SRAM only.
int counter = 0; // .bss (zero initialized)
int limit = 500; // .data (value stored in flash, copied to SRAM)
static byte history[64]; // .bss, 64 bytes
const char name[] = "node"; // .data on AVR, 5 bytes in SRAMThe last line surprises many people. On AVR, a const array is still copied into SRAM unless you mark it PROGMEM. The const keyword stops your code from changing it. It does not move it to flash. Later chapters show how F() and PROGMEM fix this.
Static data has one important property: its cost is predictable and permanent. If globals take 1800 of 2048 bytes, only 248 bytes remain for the heap and stack for the whole life of the sketch.
The heap
The heap holds memory you request at run time. In Arduino code you rarely call malloc() yourself, but you use it indirectly every time you use String, or a library that calls new.
Key facts about the AVR heap:
- It starts right after
.bss(the linker symbol__heap_start) and grows upward. malloc()tracks the highest address in use in a variable called__brkval. When no allocation has happened yet,__brkvalis 0.- Freed blocks go onto a free list and can be reused, but the allocator does not move live blocks to close gaps. That gap pattern is fragmentation, which a later chapter covers.
malloc()returnsNULLwhen it cannot satisfy a request. Most Arduino code never checks that, so failure appears as odd behavior instead of an error message.
The stack
The stack holds the working state of running functions. Each call pushes a frame containing:
- the return address (2 bytes on the ATmega328P, which has a 16-bit program counter),
- saved registers that the function uses,
- the function's local variables,
- arguments that do not fit in registers.
When the function returns, its frame is popped and the space is reused automatically. The stack pointer starts at RAMEND (address 0x08FF on the Uno) and moves downward as calls nest.
Interrupts also use the stack. When an interrupt fires, the CPU pushes the return address and the interrupt handler may push more registers. The worst-case stack depth therefore includes your deepest call chain plus an interrupt that fires at the worst moment.
The stack is the least predictable region because its depth depends on what the program is doing right now. A function with char buf[200] as a local variable takes 200 bytes of stack for as long as it runs, even if it only writes ten of them.
Seeing the regions in code
You can print the addresses of the boundaries to confirm the layout. This sketch prints the start of the heap, the current heap top, and the address of a local variable (which is on the stack).
extern int __heap_start;
extern int *__brkval;
int globalValue = 7;
int globalZero;
void setup() {
Serial.begin(9600);
int local = 0;
Serial.print(F("globalValue (.data): "));
Serial.println((int)&globalValue);
Serial.print(F("globalZero (.bss): "));
Serial.println((int)&globalZero);
Serial.print(F("heap start: "));
Serial.println((int)&__heap_start);
Serial.print(F("heap top (brkval): "));
Serial.println((int)__brkval);
Serial.print(F("local (stack): "));
Serial.println((int)&local);
}
void loop() {
}On an Uno the addresses are decimal numbers between about 256 and 2303. The local variable's address is near 2300, close to RAMEND. The two globals are low, and heap start sits just above them. Your exact numbers vary with the Arduino core version and the sketch.
How free memory is defined
The "free RAM" that most tools report is the gap between the heap top and the current stack pointer. That is the same calculation as in the freeRam() helper:
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() {
}The address of v, a local variable, approximates the current stack pointer. Subtracting the heap top gives the gap in bytes. Two limits apply:
- It is a snapshot. The value is valid only at the moment of the call and inside that call depth. A deeper call later may use more stack.
- It ignores holes in the heap. Free blocks below
__brkvalare not counted, even thoughmalloc()could reuse them.
For these reasons, measure at the point in the program where stack use is highest, and treat a low result as a warning even if it is not zero.
What happens when regions collide
The regions have no hardware protection. The ATmega328P has no memory management unit, so nothing stops one region from writing over another.
| Collision | Cause | Typical result |
|---|---|---|
| Stack grows into the heap | Deep calls, large local arrays, recursion | Heap data is corrupted, strings change on their own |
| Heap grows into the stack | Many or large allocations, growing `String` objects | Return addresses or locals are overwritten, crashes and resets |
| Either runs into `.bss` | Very little RAM left after globals | Global variables change value unexpectedly |
The heap checks nothing against the stack. malloc() does include a safety margin check against the stack pointer, so it may return NULL before a collision, but the stack has no such check against the heap. Because the stack can overwrite heap data silently, the failure often shows up far from the code that caused it.
A worked budget
Suppose a sketch reports that its globals use 1450 bytes. Here is how to budget the rest of the 2048 bytes.
- Static data: 1450 bytes. This leaves 598 bytes.
- Heap: assume
Stringuse peaks at 120 bytes, and fragmentation wastes another 60. That leaves 418 bytes. - Stack: the deepest call chain uses about 40 bytes of frames, plus a 64-byte local buffer, plus about 30 bytes for an interrupt. That is 134 bytes. This leaves 284 bytes of margin.
A margin of a few hundred bytes is healthy. A margin under about 100 bytes deserves action, because the estimates above are rarely exact.
Practical rules that follow from the layout
- Treat global size as a fixed cost. Reduce it first, because it is permanent.
- Avoid large local arrays. If a buffer is needed for the whole program, make it a global or
staticso the cost shows up in the build report instead of appearing only at run time. - Avoid recursion unless the depth is bounded and small.
- Avoid repeatedly growing and freeing heap objects in
loop(). - Measure free RAM at several points, not just in
setup().
Exercises
Exercise
A sketch declares const char msg[] = "Hello, sensor"; as a global on an Uno. Where is it stored, and how many bytes of SRAM does it use?
Show answer
On AVR the array is placed in .data, so it is copied from flash into SRAM at startup. The string has 13 characters plus the terminating null, so it uses 14 bytes of SRAM (and 14 bytes of flash for the initial copy). const does not move it to flash. Marking it PROGMEM would.
Exercise
The build report says global variables use 1900 bytes of the 2048 available. A function declares char buf[100] as a local variable. Why is this a problem even though 148 bytes remain?
Show answer
The local array lives on the stack, and the stack must also hold return addresses, saved registers and other locals, plus any interrupt that fires. Only 148 bytes are left for the heap and the stack together, so the 100-byte buffer plus its function frame can leave almost nothing. The stack is likely to grow into the heap or into the static data, which corrupts variables without an error message.
Exercise
Why does the freeRam() helper take the address of a local variable?
Show answer
A local variable lives on the stack, so its address is close to the current stack pointer. Subtracting the heap top (__brkval, or __heap_start if nothing has been allocated) from that address gives the gap between the heap and the stack, which is the free SRAM at that moment.