0x01000x08FFSRAM · 2,048 byteshole642 B freereadings[400] · 800 Ba 202 Bbc 302 Bc ???line 202 Bwindow · 802 B1int readings[400];2void loop() {3 report(); // line[200]4 int *a = (int*)malloc(200);5 char *b = (char*)malloc(100);6 free(a);7 int *c = (int*)malloc(300);8 smooth(); // window[400]9}F("Hi")flash 32 KB800202202102302702NULL802F()SPtop
Back: the 2,048 bytes of SRAM to scale, low addresses left, high rightFront: the sketch's loop() and the 32 KB flashTokens: byte counts; markers: the heap top and the stack pointer (SP)The Arduino Uno's 2,048 bytes of SRAM to scale, from 0x0100 to 0x08FF: globals at the bottom, the heap growing up after them, the stack growing down from the top. One pass of loop(): report()'s frame comes and goes, malloc() hands out a, b and c, free(a) leaves a hole, and 642 bytes stay free. malloc(700) is refused with NULL, but smooth()'s 802-byte frame is not checked: it overwrites 160 bytes of c.

One strip of SRAM

  1. 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.

The stack

The heap

When they meet

What happens

;; step 1/10 · sram
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

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.