Sub topic 9
The String class versus C strings
This chapter assumes you can write and upload a sketch, know C/C++ basics (arrays, pointers, functions), and can use the Serial Monitor. It also assumes you have read the earlier chapters on SRAM layout and dynamic allocation. The examples target AVR boards such as the Uno, which has 2 KB of SRAM.
Two ways to hold text
Arduino gives you two ways to store text.
- A C string is a
chararray that ends with a zero byte ('\0'). You choose its size at compile time, and the compiler places it in static data or on the stack. - The
Stringclass is a C++ object. It holds a pointer to a buffer on the heap, plus a capacity and a length. The object is 6 bytes on AVR, and the text it manages lives in a separate heap block that grows as needed.
String is convenient. You can write a + b, s.indexOf(','), or s += 42 without thinking about buffer sizes. The cost is that every String depends on malloc() and realloc(), and on a 2 KB heap that dependency is the main source of strange crashes.
What a String actually costs
Consider this line:
String s = "Reading: ";Two copies of the text now exist. The literal "Reading: " is stored in SRAM by the compiler. The String constructor then copies it into a heap block of length plus one byte, and the allocator adds a couple of bytes of bookkeeping. You pay for the text twice, plus the 6-byte object.
Growth is the bigger problem. When you append beyond the current capacity, the class allocates a larger block, copies the old text, and frees the old block. During that copy both blocks exist at once, so peak usage is the old size plus the new size.
How String fragments the heap
The heap hands out blocks from one contiguous region. When blocks are freed, the gaps they leave are reusable only for requests that fit. Suppose a sketch builds a status message every second:
- The first message allocates a 20-byte block.
- A second
Stringallocates 30 bytes after it. - The first message grows, so a 30-byte block is allocated, the 20-byte block is freed, and a 20-byte hole remains.
- A later request for 24 bytes cannot use the 20-byte hole, so the heap extends further.
After many cycles the heap holds several small unusable holes. The total free memory can be hundreds of bytes while no single block is large enough. The allocation then fails. The failure is quiet: an AVR String that cannot allocate becomes empty or truncated, and the sketch keeps running with wrong data.
placeholderThe paragraph above describes the cycle. The diagram below summarizes how to choose between the two approaches.
Using C strings safely
A fixed buffer has a known size, never moves, and never touches the heap. The usual rule is that you must never write past the end. Prefer functions that take a size.
char line[32];
void setup() {
Serial.begin(9600);
int temperature = 23;
snprintf(line, sizeof(line), "Temp: %d C", temperature);
Serial.println(line);
}
void loop() {
}snprintf() writes at most sizeof(line) bytes, including the terminating zero, and truncates anything longer. Compare that with sprintf() and strcpy(), which have no limit and will overwrite whatever follows the buffer.
Common C string functions
| Task | Function | Note |
|---|---|---|
| Length | `strlen(s)` | Counts bytes up to `'\0'`, so it is O(n). |
| Copy with limit | `strncpy(dst, src, n)` | Does not add `'\0'` if `src` fills `n` bytes. Set `dst[n - 1] = '\0'` yourself. |
| Compare | `strcmp(a, b)` | Returns 0 when equal, not true. |
| Find character | `strchr(s, c)` | Returns a pointer or `NULL`. |
| Format | `snprintf(buf, n, fmt, ...)` | Bounded, and the safest way to build a line. |
| Parse number | `atoi(s)`, `atol(s)`, `atof(s)` | No error reporting. Invalid text gives 0. |
Floating-point values
The default AVR printf family does not support %f. The output is a literal ?. Convert the number with dtostrf() first, then format the result as text.
char num[10];
char line[24];
void setup() {
Serial.begin(9600);
float volts = 4.987;
dtostrf(volts, 5, 2, num);
snprintf(line, sizeof(line), "V=%s", num);
Serial.println(line);
}
void loop() {
}The arguments to dtostrf() are the value, the minimum field width, the number of decimals, and the output buffer. Size the buffer for the widest value you expect, plus the terminator.
Reading input without a String
Reading a line from the serial port into a fixed buffer shows the bounds check you must write yourself.
const uint8_t LINE_SIZE = 32;
char input[LINE_SIZE];
uint8_t length = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') {
input[length] = '\0';
Serial.print(F("Got: "));
Serial.println(input);
length = 0;
} else if (c != '\r' && length < LINE_SIZE - 1) {
input[length++] = c;
}
}
}The test length < LINE_SIZE - 1 reserves one byte for the terminator. Extra characters in an over-long line are dropped. You could instead discard the whole line, which is often the better behavior for commands.
Using String more carefully
Sometimes String is the right tool, for example in a short-lived sketch that parses a few messages. You can reduce the risk with three habits.
- Call
reserve()once so the buffer is allocated up front and does not grow. - Keep the
Stringas a global, or reuse one object, instead of creating and destroying temporaries inloop(). - Pass literals through
F()so the text exists only in flash and the heap copy is the only SRAM cost.
String message;
void setup() {
Serial.begin(9600);
message.reserve(40);
message = "Reading: ";
message += 512;
Serial.println(message);
}
void loop() {
}reserve(40) allocates 40 characters plus the terminator in one block. Appending within that limit never reallocates. Note that reserve() is a request, and it can fail. Check message.length() or the result of the operation if the data matters.
Using F() with String looks like this:
String status;
void setup() {
Serial.begin(9600);
status.reserve(32);
status = F("Sensor ");
status += F("ready");
Serial.println(status);
}
void loop() {
}Converting between the two
You can move between the two types when a library requires one or the other.
Stringto C string:s.c_str()returns a read-onlyconst char *into the String's buffer. The pointer becomes invalid as soon as the String changes or is destroyed.Stringto a copy:s.toCharArray(buf, sizeof(buf))copies at mostsizeof(buf) - 1characters and terminates the result.- C string to
String:String s(buf);allocates a heap copy.
Trade-offs at a glance
| Aspect | C string | String |
|---|---|---|
| Heap use | None | One block per object, plus reallocation |
| Maximum length | Fixed, you check it | Grows until memory runs out |
| Failure mode | Buffer overflow if unchecked | Silent truncation or empty text |
| Ease of use | Needs care with sizes | Operators and helper methods |
| Fragmentation risk | None | High on 2 KB boards |
| Code size | Smaller | Larger, since the class pulls in more code |
On boards with much more RAM, such as an ESP32 or a Cortex-M board, String is far less risky. The 2 KB Uno and the Nano with an ATmega328P are where the habits in this chapter matter.
Summary of rules
- Prefer
charbuffers withsnprintf()for text that lives in long-running sketches. - If you use
String, reserve its size, reuse objects, and avoid building text from chained temporaries. - Always leave room for the terminating
'\0'. - Keep literals in flash with
F(). - Use
dtostrf()for floats on AVR.
Exercise
A sketch on an Uno runs fine for several hours, then prints truncated lines and eventually resets. loop() contains String line = "T=" + String(temp) + " C"; Serial.println(line);. Free RAM measured at startup is 900 bytes. Explain the likely cause and rewrite the line without String.
Show answer
Each pass creates several temporary Strings on the heap and frees them in an order that leaves small holes. Over many iterations the heap fragments, so a later allocation fails even though total free RAM looks large. A failed allocation gives truncated or empty text, and the heap eventually grows into the stack, which causes the reset. A fixed buffer avoids this: declare char line[24]; as a global, then use snprintf(line, sizeof(line), "T=%d C", temp); Serial.println(line);. If temp is a float, convert it with dtostrf() first.
Exercise
Why does strncpy(dst, src, sizeof(dst)) still risk a bug, and how do you fix it?
Show answer
If src is as long as or longer than sizeof(dst), strncpy() copies exactly that many bytes and does not write a terminating zero, so dst is not a valid C string. Fix it by setting the last byte yourself with dst[sizeof(dst) - 1] = '\0'; after the copy, or by using snprintf(dst, sizeof(dst), "%s", src), which always terminates.