Sub topic 10
Fixed-size buffers and bounded formatting
Assume you can write Arduino functions, use arrays and pointers, and inspect output in the Serial Monitor. This chapter uses C strings: null-terminated character arrays that store text. A fixed-size buffer gives text a known maximum size and avoids allocating memory from the heap while the sketch runs.
Why fixed-size buffers matter
A buffer is a region of memory reserved for data. For example:
char line[32];This reserves 32 bytes, including space for the terminating '\0' character. A C string stored in this buffer can contain at most 31 visible characters.
Unbounded functions such as sprintf() do not know the buffer's capacity. If formatted output is longer than the array, the function writes beyond the array. This is a buffer overflow. It can corrupt another variable, damage the stack, or make the board reset.
snprintf() is bounded formatting. It receives the buffer size and writes no more than that size, including the terminator.
char line[32];
void setup() {
Serial.begin(9600);
int temperature = 23;
int humidity = 58;
int needed = snprintf(
line,
sizeof(line),
"Temp: %d C, Hum: %d%%",
temperature,
humidity
);
if (needed < 0) {
Serial.println(F("Formatting failed"));
} else if (needed >= sizeof(line)) {
Serial.println(F("Output was truncated"));
Serial.println(line);
} else {
Serial.println(line);
}
}
void loop() {
}The return value is important:
- A negative value indicates a formatting error.
- Otherwise, the value is the number of characters that would have been produced, not counting
'\0'. - If that value is greater than or equal to the buffer capacity, the result was truncated.
The buffer still contains a valid terminated string when snprintf() succeeds, even if the displayed text is incomplete.
Place buffers deliberately
A global or static buffer uses the sketch's static SRAM area. A local buffer normally uses the stack. Both approaches avoid heap allocation, but a large local buffer exists only while its function is active and increases stack use.
char output[40];
void printReading(int value) {
int written = snprintf(output, sizeof(output), "Reading: %d", value);
if (written >= 0 && written < sizeof(output)) {
Serial.println(output);
} else {
Serial.println(F("Reading does not fit"));
}
}
void setup() {
Serial.begin(9600);
printReading(512);
}
void loop() {
}For reusable code, pass the buffer and its capacity into a function. This makes the limit visible at the point where the function writes.
flowchart TD
A[Choose buffer capacity] --> B[Call snprintf with sizeof buffer]
B --> C{Return value fits?}
C -->|Yes| D[Use complete string]
C -->|No| E[Handle truncation or report error]
C -->|Negative| F[Report formatting failure]Common errors
- Forgetting the terminator: Allocate one extra byte for
'\0'. - Using
sizeofon a pointer: Insidevoid f(char *buffer),sizeof(buffer)is the pointer size, not the array capacity. Pass the capacity separately. - Ignoring truncation: A partial command or filename may be unsafe or misleading. Reject it when complete output is required.
- Choosing an arbitrary small buffer: Calculate the longest possible text, including signs, digits, spaces, punctuation, and the terminator.
- Using
%swith an invalid pointer: The source string must also be null-terminated.
Exercise
A 16-byte buffer receives snprintf(buffer, sizeof(buffer), "Value: %d", 123456). What should the code check before treating the result as complete?
Show answer
It should check that the return value is nonnegative and less than sizeof(buffer). A value of 16 or more means the output was truncated.