Sub topic 9
The String class versus C strings
Assume you know variables, arrays, functions, pointers, and how to use the Serial Monitor. This chapter focuses on AVR-based boards such as the Arduino Uno, where SRAM is small and heap fragmentation can cause failures.
Two ways to store text
String is an Arduino C++ class that stores text and manages its memory automatically. You can append values with +=, compare text easily, and find substrings with methods such as indexOf().
A C string is an array of char values that ends with a null character, written as '\0'. The null character tells functions where the text ends. The array must have room for both the visible characters and this final character.
char label[12] = "Temperature";
void setup() {
Serial.begin(9600);
Serial.println(label);
}
void loop() {
}The array above needs 12 bytes: 11 bytes for Temperature and 1 byte for '\0'.
| Feature | `String` | C string |
|---|---|---|
| Storage | Usually heap allocation | Often a fixed array |
| Ease of use | High | Requires more care |
| Heap fragmentation risk | Possible on small AVR boards | Low with fixed buffers |
| Size control | Dynamic, unless reserved | Explicit buffer size |
| Best fit | Short-lived or simple text | Long-running, memory-sensitive sketches |
Why repeated `String` changes can fragment the heap
The heap is the area used for dynamic allocation. A String may request a larger block when text grows. The old block is released, leaving a free gap. Later allocations may not fit in the gaps even when the total free memory seems sufficient. This condition is called heap fragmentation.
A sketch can work during testing and fail after hours of operation because repeated assignments create a changing pattern of allocated and released blocks.
String message;
void setup() {
Serial.begin(9600);
message.reserve(40); // Allocate storage once.
}
void loop() {
int reading = analogRead(A0);
message = "Reading: ";
message += reading;
Serial.println(message);
delay(1000);
}reserve(40) reduces reallocations while the message stays within 40 characters. It does not make unlimited growth safe. If the text exceeds the reserved capacity, another allocation may still occur.
Fixed buffers and bounded formatting
A fixed buffer gives you direct control over SRAM. snprintf() formats values and receives the buffer size, so it limits the number of characters written.
char line[32];
void setup() {
Serial.begin(9600);
int temperature = 23;
int written = snprintf(line, sizeof(line), "Temp: %d C", temperature);
if (written < 0) {
Serial.println(F("Formatting failed"));
} else if (written >= sizeof(line)) {
Serial.println(F("Text was truncated"));
} else {
Serial.println(line);
}
}
void loop() {
}Always pass sizeof(buffer) rather than a number you type separately. If you later change the buffer size, the formatting limit changes with it.
Do not use unbounded functions such as strcpy() or sprintf() unless you can prove the destination is large enough. Writing past an array can corrupt other variables, the heap, or the stack.
Choosing between them
Use a fixed C string when the message has a known maximum length, the sketch runs continuously, or free SRAM is close to its limit. Use String when the code benefits from simple text operations and memory pressure is low. For a String, reserve a realistic maximum and avoid constructing many temporary values.
Exercise
Why does a fixed char buffer often reduce memory risk compared with repeatedly growing a String on an Uno?
Show answer
Its storage is allocated once at a known size, so it does not repeatedly request and release heap blocks that can fragment SRAM.