Living in 2 KB of RAM: stack, heap and globals
About this lesson
An Arduino Uno R3 has just 2,048 bytes of SRAM, and every variable in your sketch has to fit. Follow one pass of a sketch byte by byte: globals fill the bottom, malloc() grows the heap up, function calls push stack frames down from the top, free() leaves a hole, and finally a large local array pushes the stack into the heap without any warning. The C++ lessons “Variables on the stack”, “The heap: new and delete” and “Pointers” cover the language side; here we look at what it costs on a ATmega328P.
2,048 bytes for everything
The Uno's ATmega328P has 2 KB of SRAM: 2,048 bytes at addresses 0x0100 to 0x08FF. Every variable lives here. Three users share it: globals at the bottom, the heap above them, and the stack coming down from the top.
SRAM 2,048 bytes 0x0100 .. 0x08FF bottom globals (fixed when the sketch is built) above heap (grows up: malloc) top stack (grows down: function calls) below 0x0100: the chip's registers, not your memory
Read the lesson step by step
2,048 bytes for everything
The Uno's ATmega328P has 2 KB of SRAM: 2,048 bytes at addresses 0x0100 to 0x08FF. Every variable lives here. Three users share it: globals at the bottom, the heap above them, and the stack coming down from the top.
SRAM 2,048 bytes 0x0100 .. 0x08FF bottom globals (fixed when the sketch is built) above heap (grows up: malloc) top stack (grows down: function calls) below 0x0100: the chip's registers, not your memoryGlobals take the bottom
readings is a global: declared outside any function, it lives for the whole run. An int is 2 bytes, so 400 of them take 800 bytes, from 0x0100 to 0x041F. That space is reserved before setup() runs.
line 1 int readings[400]; size 400 x 2 bytes = 800 bytes where 0x0100 .. 0x041F left 1,248 bytes for the heap and the stackA call pushes a frame
The stack starts at the top, 0x08FF, and grows down. Calling report() pushes a frame: the 2-byte return address plus its local array line, 200 bytes. The stack pointer, SP, drops at least 202 bytes, to 0x0835.
line 3 report(); frame return address 2 bytes char line[200] 200 bytes at least 202 bytes: 0x0836 .. 0x08FF SP 0x08FF -> 0x0835Return pops it
When report() returns, SP moves back up to 0x08FF and those 202 bytes are free again. A local lives only while its function runs. The stack cleans up after itself, with no code from you.
report() returns SP 0x0835 -> 0x08FF line[200] is gone: its bytes are free for the next callThe heap grows up
malloc(200) asks for memory while the sketch runs. It comes from the heap, which starts right after the globals, at 0x0420. A 2-byte size header goes in front, so a uses 202 bytes. Then b uses 102. The heap top climbs to 0x0550.
line 4 a = malloc(200) 2 + 200 = 202 bytes 0x0420 .. 0x04E9 line 5 b = malloc(100) 2 + 100 = 102 bytes 0x04EA .. 0x054F heap top 0x0420 -> 0x0550free() leaves a hole
free(a) gives its 202 bytes back, but b still sits above them, so the heap cannot shrink. Then malloc(300) needs 302 bytes: too big for the hole, so it goes on top. The heap top climbs to 0x067E. Unusable holes like this are fragmentation.
line 6 free(a) hole of 202 bytes at 0x0420; b is above it line 7 c = malloc(300) needs 302 > 202: does not fit the hole placed on top 0x0550 .. 0x067D heap top 0x0550 -> 0x067E in use 404 bytes, but the heap spans 606The free space between
Free memory is the gap between the heap top, 0x067E, and the stack at the top: 642 bytes. The heap grows up into it and the stack grows down into it. Nothing in the chip keeps them apart.
heap top 0x067E stack 0x08FF (SP, between calls) free 0x0900 - 0x067E = 642 bytes no hardware guard between the heap and the stackmalloc() checks first
Suppose loop() now asked for malloc(700): 702 bytes. avr-libc will not grow the heap within 32 bytes of the stack, so malloc returns NULL, a pointer to nothing. Always check the result before you use it.
malloc(700) needs 2 + 700 = 702 bytes free 642 bytes, minus the 32-byte margin = 610 702 > 610 -> returns NULL int *p = (int*)malloc(700); if (p == NULL) { /* no memory: cope */ }The stack never checks
smooth() declares int window[400]: 800 bytes. Its frame needs at least 802, but only 642 are free. SP drops to 0x05DD and the frame silently overwrites the top 160 bytes of c. No error: values change, and the sketch may crash.
line 8 smooth(); int window[400] frame 2 + 800 = 802 bytes > 642 free SP 0x08FF -> 0x05DD overlap 0x05DE .. 0x067D: 160 bytes of c overwritten no check, no error message: anything can happenLiving in 2 KB
Keep big arrays out of functions, avoid malloc() in loop(), and check what malloc() returns. Wrap fixed text in F(), as in Serial.print(F("Hi")), so it stays in flash instead of being copied into SRAM at start-up.
big arrays global, sized to what you need malloc() / free() in loop() -> holes; avoid malloc() result check for NULL fixed text Serial.print(F("Logging...")); stays in flash recursion every call adds a frame: keep it shallow
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01On the Uno an int is 2 bytes. How much SRAM does the global int readings[400]; take?
400 ints × 2 bytes = 800 bytes of SRAM, reserved for the whole run, before setup() starts.
02Which way does the stack grow on the ATmega328P?
The datasheet says the stack grows from higher to lower addresses, and the stack pointer starts at the last SRAM address, 0x08FF. The heap grows the other way, up from the end of the globals.
03The heap holds a (202 bytes) and then b (102 bytes). After free(a), malloc(300) is called. Where does the new block go?
The request needs 302 bytes with its 2-byte header, more than the 202-byte hole, so avr-libc extends the heap above b. The hole stays unused: that is fragmentation.
04Only 642 bytes are free between the heap and the stack. What happens when a function with an 800-byte local array is called?
Nothing checks a function call. Its frame is pushed regardless, overwriting whatever heap data lies below, with no error message. The sketch may then misbehave or crash.
05Why write Serial.print(F("Logging...")) instead of Serial.print("Logging...")?
A plain string literal is normally copied into SRAM when the board starts. F() keeps it in the 32 KB of flash, which leaves those bytes free for your variables.
Glossary
- SRAM
- The microcontroller's working memory. The ATmega328P has 2,048 bytes, at addresses 0x0100 to 0x08FF. Its contents are lost at power off.
- Global variable
- A variable declared outside any function. Its space is fixed when the sketch is built and it lives for the whole run.
- Stack
- Memory for function calls: each call pushes a frame (return address and local variables) and each return pops it.
- Stack frame
- The block one function call takes on the stack: its return address, its local variables and any registers it saves.
- Stack pointer (SP)
- A register holding the address of the next free byte on the stack. It moves down on a push and up on a pop.
- Heap
- Memory handed out while the program runs by malloc() (or new) and given back with free() (or delete).
- Fragmentation
- Free heap space split into holes too small for the next request, so memory is wasted even though it is free.
- F() macro
- Arduino wrapper that keeps a fixed string in flash instead of copying it into SRAM.
Notes and sources
- The picture puts readings at 0x0100. In a real build the Arduino core adds a few globals of its own (for example, the counters behind millis()) and the linker decides the exact order, so readings may start a few bytes later. Initialised globals (.data) come first, then zeroed ones (.bss), then the heap.
- A frame is at least the return address plus the locals. The compiler may also save registers on the stack, so real frames are a little bigger. loop() and main() keep a few bytes on the stack too, so the true free space is slightly less than 642 bytes. We assume report() and smooth() really use their arrays; an unused local can be removed by the compiler.
- The card follows one pass of loop(). The sketch never frees b and c, so a second pass would leak them: a real sketch must free what it allocates, or better, not allocate in loop() at all.
- avr-libc's __malloc_margin (32 bytes by default) is only a guess at how deep the stack will go. It stops malloc() from growing into the stack, but nothing stops a deep call from growing into the heap.
- The AVR stack pointer points at the next free byte: a push writes at SP and then decrements it, so a frame of n bytes below an empty stack fills 0x0900 - n to 0x08FF and leaves SP one byte below it.
Quiz Unlocks after the last step.