C Programming • C17 baseline, standards-specific features labeled
C Strings and Safe Formatting
Understand null-terminated character arrays and use bounded operations for destination buffers.
A C string is a sequence of characters ending with a null character. The array must have room for both its visible characters and that terminator. Use snprintf with the destination size when formatting into a fixed buffer, and check its return value if truncation matters.
Example
#include <stddef.h>
#include <stdio.h>
int main(void) {
char message[32];
int written = snprintf(message, sizeof message, "Item %d", 17);
if (written < 0 || (size_t)written >= sizeof message) {
return 1;
}
puts(message);
return 0;
}
What to expect
Item 17
Key idea: String functions need valid terminated inputs and enough destination capacity.