Sub topic 8
Why dynamic allocation fragments a 2 KB heap
This chapter assumes that you can write and upload an Arduino sketch, use the Serial Monitor, and understand variables, arrays, functions, and pointers.
An Arduino Uno has 2 KB of SRAM. That memory holds global variables, local variables, the heap, and the stack. The heap is the area used by dynamic allocation, such as malloc, free, and the Arduino String class.
What heap fragmentation means
Dynamic allocation requests a block of memory while the program runs. For example, malloc(20) asks for a block large enough to hold 20 bytes. When the block is no longer needed, free() returns it to the heap.
The problem starts when blocks have different sizes and are released in different orders:
[used 40][free 20][used 80][free 30][used 50]There are 50 free bytes in the gaps, but no single free block is 50 bytes long. A later request for 50 bytes can fail even though the total free memory appears sufficient. This condition is called heap fragmentation.
The heap shares SRAM with the stack. A fragmented heap can also leave less usable space between the heap and stack, increasing the chance of a collision.
| Allocation pattern | Likely result |
|---|---|
| Allocate fixed-size blocks and keep them | Predictable usage |
| Repeatedly grow and shrink different objects | Fragmentation |
| Use fixed-size arrays | No heap fragmentation |
Why `String` can cause fragmentation
A String stores its characters in a dynamically allocated buffer. When you append text and the current buffer is too small, it may allocate a larger buffer, copy the old text, and release the old buffer.
Repeated operations with changing message lengths can create many holes:
String message;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
message = "Sensor value: ";
message += sensorValue;
Serial.println(message);
delay(100);
}This sketch may work for a while, but repeated allocation and release can fragment SRAM on small AVR boards. The exact behavior depends on the String implementation and the message sizes.
Reserve storage when you know an upper bound. The buffer is allocated once and reused:
String message;
void setup() {
Serial.begin(9600);
message.reserve(24);
}
void loop() {
int sensorValue = analogRead(A0);
message = "Sensor value: ";
message += sensorValue;
Serial.println(message);
delay(100);
}reserve(24) does not make the sketch use no dynamic memory. It reduces later reallocations while the message stays within the reserved capacity.
Prefer fixed-size storage
A character array, also called a C string buffer when it contains a null-terminated string, has a fixed size. snprintf() formats text while limiting the number of characters written.
char message[32];
void setup() {
Serial.begin(9600);
int sensorValue = analogRead(A0);
snprintf(message, sizeof(message), "Sensor value: %d", sensorValue);
Serial.println(message);
}
void loop() {
}sizeof(message) gives the buffer capacity. snprintf() writes at most that many bytes, including space for the terminating null character. If the formatted result is too long, it is truncated instead of writing beyond the array.
For long-running Uno projects, fixed-size buffers are often easier to reason about than repeated heap allocation. Avoid malloc() unless you have a specific need and can control the allocation lifetime. Allocate long-lived objects during setup, reuse them, and release them in a predictable order.
Exercise
Why can a 50-byte allocation fail when 50 bytes are free in total?
Show answer
The free bytes may be split across several smaller gaps, with no single contiguous block large enough for the request.