Format into a Bounded Buffer
Build a label without overrunning its array
The supply desk builds a crate label in a fixed-size array before printing it. snprintf takes the buffer capacity, including room for the terminating null character. It returns the number of characters the full result would need, excluding the terminating null character, or a negative value on error. A return value at least as large as the capacity means truncation.
\0 is the null character that ends a C string; it is different from NULL, the null pointer used in allocation checks.
snprintf writes into the array, not to stdout. puts later prints the stored string and adds a newline. Supplying a capacity only helps if it is the real capacity: here label is an actual array, so sizeof label is its byte size. Inside a function receiving a char *, sizeof that pointer would not tell you the buffer capacity; pass the capacity separately.
#include <stdio.h>
int main(void) {
char label[32];
int written = snprintf(label, sizeof label, "%s #%d", "Crate", 7);
if (written < 0 || (size_t)written >= sizeof label) {
return 1;
}
puts(label);
return 0;
}
Run it to see Crate #7. That text uses eight characters, so a complete stored string needs nine slots including \0. written is 8, not 9, and not the capacity 32.
The || condition checks for a negative result first. If that check succeeds, C does not evaluate the right side. Otherwise the cast to size_t lets us compare the nonnegative length with the array's capacity. An equal result also means failure to fit: the full text would leave no room for its terminator, so the stored text must be shortened.
This second, separate example deliberately uses an eight-byte array. It prints a status message instead of treating the shortened text as a complete label:
#include <stdio.h>
int main(void) {
char label[8];
int written = snprintf(label, sizeof label, "%s #%d", "Crate", 7);
if (written < 0) {
return 1;
}
if ((size_t)written >= sizeof label) {
puts("Label did not fit");
return 0;
}
puts(label);
return 0;
}
Here written is still 8: it describes the full result, not how much was stored. The array contains Crate # followed by \0, so the program reports Label did not fit rather than printing an incomplete label.
With a positive capacity and a successful formatting operation, snprintf writes at most capacity minus one characters and terminates what it stores. It prevents writing past this correctly sized buffer, but it cannot decide whether a shortened label is acceptable. Our program rejects truncation. Do not substitute sprintf, which has no capacity argument.