Sub topic 10
Fixed-size buffers and bounded formatting
This chapter assumes you know C arrays and pointers, can read the String discussion from the previous chapter, and can use the Serial Monitor. It covers how to build and store text in memory whose size you chose at compile time. It also covers how to keep that text from overrunning the memory.
Why a fixed buffer
A String grows on the heap, and repeated growth can fragment a 2 KB heap. A fixed-size char array has none of that cost.
- It is allocated once, at compile time, so the build report counts it.
- It never moves, so it cannot fragment the heap.
- Its worst-case size is visible in the source.
The cost is that you must pick the size and enforce it. C will not stop you from writing past the end of an array. On an AVR board, an overrun silently overwrites a neighbouring variable, so the damage shows up somewhere unrelated.
How a C string uses a buffer
A C string is a char array that ends with a null byte ('\0'). A buffer declared as char name[8] holds at most 7 visible characters plus the terminator.
char name[8]; // 7 characters + '\0'Forgetting the terminator is the most common off-by-one error. Functions such as Serial.println(name) and strlen(name) keep reading until they find a zero byte. Without one they read past the array into whatever follows it in SRAM.
Formatting with snprintf
snprintf(buffer, size, format, ...) writes formatted text into buffer. It never writes more than size bytes, including the terminator. It always terminates the result when size is greater than zero.
char line[32];
void setup() {
Serial.begin(9600);
int temperature = 23;
snprintf(line, sizeof(line), "Temp: %d C", temperature);
Serial.println(line);
}
void loop() {
}Use sizeof(line) instead of typing 32 again. If you later change the declaration, the bound follows it. Do not use the unbounded sprintf. It has no size argument, so a longer-than-expected value overruns the buffer.
Format specifiers on AVR
An int is 16 bits on an Uno, so the length modifiers matter.
| Type | Specifier | Note |
|---|---|---|
| `int` | `%d` | 16-bit on AVR |
| `unsigned int`, `uint16_t` | `%u` | |
| `uint8_t` | `%u` | Promoted to `int` when passed |
| `long` | `%ld` | `%d` would print the wrong value |
| `unsigned long` | `%lu` | Use for `millis()` |
| `char *` | `%s` | Must point to a terminated string |
| `float` | `%f` | Not supported by default, prints `?` |
Floating-point values
The avr-libc printf family does not support %f in the default Arduino build. The output is a ?. Convert the number with dtostrf() first, then insert it with %s.
char num[8];
char line[24];
void setup() {
Serial.begin(9600);
float volts = 4.987;
dtostrf(volts, 1, 2, num); // minimum width 1, 2 decimals -> "4.99"
snprintf(line, sizeof(line), "Supply: %s V", num);
Serial.println(line);
}
void loop() {
}dtostrf() has no size argument. You must make num large enough for the largest value it can see, including the sign, the decimal point, and the terminator.
Detecting truncation
snprintf returns the number of characters it would have written if the buffer were unlimited, not counting the terminator. If that value is greater than or equal to the buffer size, the output was cut short.
char line[16];
void setup() {
Serial.begin(9600);
int temperature = 23;
int n = snprintf(line, sizeof(line), "Temperature: %d C", temperature);
Serial.println(line);
Serial.println(n);
if (n < 0 || n >= (int)sizeof(line)) {
Serial.println(F("Output truncated"));
}
}
void loop() {
}The full text, Temperature: 23 C, is 17 characters and needs 18 bytes with the terminator. The sketch prints Temperature: 23, then 17, then the warning. The buffer is safe, but the text is incomplete.
Keeping the format string in flash
A format string such as "Temp: %d C" is a literal. On AVR it is copied into SRAM at start-up, like any other literal. The _P variants read the format from flash instead.
#include <avr/pgmspace.h>
char line[24];
void setup() {
Serial.begin(9600);
int temperature = 23;
snprintf_P(line, sizeof(line), PSTR("Temp: %d C"), temperature);
Serial.println(line);
}
void loop() {
}PSTR() places the literal in flash, and snprintf_P reads it from there. This is the same idea as F(), applied to formatting. Use the plain snprintf with a %s argument only when the argument itself lives in SRAM. A pointer into flash needs %S (capital S) in the _P functions.
Copying strings safely
Copy functions are a second place where buffers overflow.
| Function | Problem |
|---|---|
| `strcpy(dst, src)` | No bound. Overruns `dst` if `src` is longer. |
| `strncpy(dst, src, n)` | Does not add a terminator if `src` has `n` or more characters. |
| `snprintf(dst, sizeof(dst), "%s", src)` | Bounded, and always terminated. |
A simple bounded copy:
char label[10];
void setup() {
Serial.begin(9600);
const char *source = "greenhouse-north";
snprintf(label, sizeof(label), "%s", source);
Serial.println(label); // prints "greenhous"
}
void loop() {
}If you prefer strncpy, terminate the result yourself with dst[sizeof(dst) - 1] = '\0';.
Reading input into a buffer
Serial input arrives one byte at a time, and a long line from the host can arrive without warning. A bounded reader stores bytes only while there is room and flags the overflow.
const uint8_t LINE_MAX_LEN = 24;
char lineBuf[LINE_MAX_LEN + 1]; // +1 for the terminator
uint8_t lineLen = 0;
bool overflowed = false;
void handleLine(const char *text) {
Serial.print(F("Got: "));
Serial.println(text);
}
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\r') {
continue;
}
if (c == '\n') {
if (overflowed) {
Serial.println(F("Line too long, discarded"));
} else {
lineBuf[lineLen] = '\0';
handleLine(lineBuf);
}
lineLen = 0;
overflowed = false;
} else if (lineLen < LINE_MAX_LEN) {
lineBuf[lineLen++] = c;
} else {
overflowed = true;
}
}
}The check lineLen < LINE_MAX_LEN runs before every store. The extra element in the array is reserved for the terminator, so lineBuf[lineLen] = '\0' is always in range.
Choosing a buffer size
Size the buffer for the worst case, not the typical case. Add up the longest literal text, the longest each number can be, and one byte for the terminator.
- A
uint8_tneeds up to 3 digits. - An
intneeds up to 6 characters, such as-32768. - An
unsigned longneeds up to 10 digits.
For "Temp: %d C", the literal part is 8 characters ("Temp: " is 6 and " C" is 2). With a worst-case int, that gives 14 characters plus the terminator, so 15 bytes. A buffer of 16 is enough. If you cannot compute a bound, call snprintf and check the return value during testing.
Where the buffer lives
A buffer can be global, static, or a local variable. The choice changes where it counts.
| Placement | Counted in | Notes |
|---|---|---|
| Global or `static` | Build report (global variables) | Fixed cost, visible at compile time |
| Local in a function | Stack, only while the function runs | Not in the build report, so it can hide a stack problem |
| `malloc` or `new` | Heap | Reintroduces fragmentation |
A 64-byte local buffer is 3% of an Uno's 2 KB of SRAM. It is released when the function returns, but it adds to the peak stack depth of every call chain that passes through that function. For a buffer that is reused, a global or static array makes the cost visible in the build report.
Passing a buffer to a function
Inside a function, a buffer parameter is only a pointer. sizeof then returns the pointer size, 2 bytes on AVR, not the array size. Pass the size as a separate argument.
void formatReading(char *out, size_t outSize, int value) {
snprintf(out, outSize, "Reading: %d", value); // not sizeof(out)
}
char text[20];
void setup() {
Serial.begin(9600);
formatReading(text, sizeof(text), 512);
Serial.println(text);
}
void loop() {
}Cost in flash
The first call to snprintf links the printf code into the sketch. That adds on the order of a kilobyte of flash. On a board with 32 KB of flash this is usually acceptable. If a sketch uses only a few number-to-text conversions, Serial.print() calls in sequence, or itoa() and dtostrf(), can be smaller. Compare the build report before and after to decide.
Exercise
A sketch declares char buf[10]; and calls int n = snprintf(buf, sizeof(buf), "Count: %u", 12345);. What value does n have, what does buf contain, and how do you detect the truncation?
Show answer
The full text Count: 12345 is 12 characters, so n is 12. The buffer holds 9 characters plus the terminator, so buf contains Count: 12. Truncation is detected because n >= sizeof(buf) (12 >= 10).
Exercise
Why does strncpy(dst, src, sizeof(dst)) not guarantee a valid C string, and what is a bounded alternative that does?
Show answer
If src has sizeof(dst) or more characters, strncpy copies exactly that many bytes and writes no terminator, so later string functions read past the array. Using snprintf(dst, sizeof(dst), "%s", src) always terminates the result. Alternatively, set dst[sizeof(dst) - 1] = '\0' after strncpy.