Sub topic 8
Why dynamic allocation fragments a 2 KB heap
This chapter assumes you can write and upload sketches, read C/C++ pointers, and use the Serial Monitor. It also assumes you know the earlier chapter's split of SRAM into static data, heap and stack. The examples target an AVR board with 2 KB of SRAM, such as the Uno.
What dynamic allocation does
Static data has a fixed size and address that the compiler chooses. Dynamic allocation asks for memory while the sketch runs. The calls are malloc() and free() in C, new and delete in C++, and any library code that calls them, such as String. The memory comes from the heap, which sits just above your global variables and grows upward toward the stack.
On a PC this is cheap and rarely a problem. On a 2 KB board it is risky for two reasons:
- The whole heap and stack share perhaps 1.5 KB. A few hundred bytes of waste is a large share of that.
- Nothing moves live blocks to tidy the heap. Once a block is allocated, it stays at its address until you free it.
How the AVR allocator tracks memory
The allocator in avr-libc, which Arduino AVR boards use, works like this:
- Heap growth. The heap starts at
__heap_start. The pointer__brkvalmarks the current top of memory handed out so far, and the heap grows upward from there. - Block headers. Every allocated block carries a small size header (2 bytes). A request for 100 bytes therefore consumes slightly more than 100.
- Free list. When you call
free(), the block goes onto a free list. The allocator merges neighbouring free blocks, and if the freed block touches the top of the heap it lowers__brkval. - Reuse. A later
malloc()first searches the free list for a block that is large enough. Only if none fits does it grow the heap. - Stack margin. The heap will not grow to within
__malloc_marginbytes (32 by default) of the stack pointer. This keepsmalloc()from consuming the last bytes that the stack needs.
Fragmentation happens in the free list. The memory is free, but it is split into pieces that are each too small for the next request.
A fragmentation example
Suppose the heap holds four blocks, in this order: A (500 bytes), B (100), C (500), D (100). Then you free A and C and keep B and D, because B and D are still in use.
You now have 1000 bytes sitting in the free list, plus whatever gap remains above D. A request for 700 bytes still fails. A and C are each too small, and B sits between them so they cannot merge. The gap above D is also too small.
The usual long-running cause is not a single dramatic pattern like this. It is many small allocations of varying sizes, freed in an order different from the order they were made. Each cycle leaves a few more unusable gaps.
Measuring it on a board
The freeRam() helper from the earlier chapter reports the gap between __brkval and the stack. It does not count blocks sitting in the free list. That makes it a poor fragmentation detector, because it can read high while malloc() is failing.
The sketch below adds a second measurement: the largest block malloc() can actually return right now. It then reproduces the A/B/C/D pattern.
extern int __heap_start;
extern int *__brkval;
int freeRam() {
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
size_t largestBlock() {
for (size_t size = 1024; size >= 16; size -= 16) {
void *p = malloc(size);
if (p != NULL) {
free(p);
return size;
}
}
return 0;
}
void report(const __FlashStringHelper *label) {
Serial.print(label);
Serial.print(F(": gap="));
Serial.print(freeRam());
Serial.print(F(" largest malloc="));
Serial.println(largestBlock());
}
void *grab(size_t n) {
void *p = malloc(n);
if (p != NULL) {
memset(p, 0, n);
}
return p;
}
void setup() {
Serial.begin(9600);
report(F("start"));
void *a = grab(500);
void *b = grab(100);
void *c = grab(500);
void *d = grab(100);
report(F("allocated"));
free(a);
free(c);
report(F("after free"));
void *big = malloc(700);
Serial.println(big == NULL ? F("malloc(700) failed") : F("malloc(700) ok"));
(void)b;
(void)d;
}
void loop() {
}The sizes assume an Uno with few global variables. If your globals are large, scale the block sizes down so the four blocks leave a gap smaller than the final request.
On a typical Uno you should see three things:
- At
allocated,gaphas dropped by about 1200 bytes. - At
after free,gaphas not changed, because the freed blocks went to the free list rather than back to the top. Thelargest mallocvalue is only about 500. malloc(700)fails even though roughly 1500 bytes are free in total.
Where hidden allocations come from
You do not have to write malloc() to fragment the heap. Common sources include:
Stringconcatenation. Each growth step may allocate a new buffer, copy, and free the old one. The next chapter covers this in detail.newanddeletefor objects created and destroyed duringloop().- Libraries that allocate buffers internally. Check the source of any library you call repeatedly.
realloc(), which may allocate a new block and copy, leaving the old one in the free list.
Two patterns make it worse. First, requests of varying sizes, such as text that grows by a few bytes each pass. Second, long-lived blocks allocated between short-lived ones, like B and D above, because they pin the holes in place.
Strategies that avoid fragmentation
| Strategy | How it helps | Cost |
|---|---|---|
| Use static or global buffers of fixed size | No heap involvement, size known at compile time | You must choose a maximum size |
| Allocate once in `setup()` and never free | Nothing is ever freed, so no holes appear | Memory is held for the whole run |
| Free in reverse order of allocation | Blocks merge back into the top of the heap | Needs disciplined code structure |
| Reserve capacity up front (`String::reserve()`) | One allocation instead of many growth steps | Still uses the heap |
| Use a fixed-block pool | Every block has the same size, so any hole fits any request | You write or add the pool code |
For most small sketches the first two rows are enough. Use a static buffer when you know the maximum size. Allocate once in setup() when the size depends on configuration read at start-up.
A fixed-size buffer with bounded formatting is the safe alternative to a growing string:
char line[32];
void setup() {
Serial.begin(9600);
int temperature = 23;
snprintf(line, sizeof(line), "Temp: %d C", temperature);
Serial.println(line);
}
void loop() {
}This uses 32 bytes of static data for the lifetime of the sketch. It never allocates, never fragments, and snprintf() cannot write past the end.
Checking allocations and reading failures
Always test the pointer. malloc() returns NULL on failure, and writing through a null pointer on AVR does not crash cleanly. It overwrites low addresses, which are registers and I/O space, so the sketch misbehaves in odd ways.
void setup() {
Serial.begin(9600);
uint8_t *buffer = (uint8_t *)malloc(64);
if (buffer == NULL) {
Serial.println(F("Out of memory"));
return;
}
buffer[0] = 42;
Serial.println(buffer[0]);
free(buffer);
}
void loop() {
}Fragmentation failures are intermittent. A sketch may run for hours, then fail on one request. If a failure appears only after a long runtime, or after a particular mix of inputs, suspect heap fragmentation. Log freeRam() and largestBlock() periodically. A widening difference between the two, with largestBlock() shrinking while freeRam() holds steady, is the signature of fragmentation. If both shrink together, you are consuming memory rather than fragmenting it, which points to a leak or to a stack that is growing.
Edge cases
- A leak looks similar. A leak is a block you never free and can no longer reach. The gap shrinks steadily. Fragmentation instead leaves total free memory high while the largest block shrinks.
- Freeing the top block helps. When the block touching
__brkvalis freed, the heap top drops and the gap grows back. This is why last-in, first-out freeing keeps the heap tidy. - Large boards behave differently. Boards with more SRAM tolerate the same pattern for much longer, but the mechanism is the same. Other architectures use different allocators with different merging rules.
Exercise
A sketch has 1500 bytes in its free list in total, yet malloc(700) returns NULL. freeRam() reports 200. Give two possible explanations and one measurement that would tell them apart.
Show answer
Either the free list is fragmented into pieces smaller than 700 bytes (for example, two holes of 500 bytes separated by a live block), or the free list is smaller than believed because the stack margin and headers consume the rest. Measure the largest block that malloc can return, as largestBlock() does. If it is well below 700 while the free-list total is large, the heap is fragmented.
Exercise
Why does freeing blocks in the reverse order of allocation reduce fragmentation on an AVR heap?
Show answer
Each freed block then touches the top of the heap. The allocator merges it into the top and lowers __brkval, so the heap returns to a single contiguous gap instead of leaving holes between live blocks.