Using snprintf for bounded string formatting in C
How to use C99 snprintf safely, detect truncation from its return value, and avoid sizeof mistakes with pointers.
08 Dec 2025, 03:11 UTC

The problem and the useful answer
A formatted string can easily exceed its destination buffer. Legacy functions such as sprintf and strcpy write without bounds, which is a direct path to buffer overflows. Switching to snprintf stops the overflow, but programs still fail silently when they ignore the function's return value or pass the wrong buffer size. A truncated file path or command can then be used as if it were complete.
The useful answer is to treat snprintf as both a writer and a length query. Always pass the actual array size—sizeof(buffer), never sizeof(pointer)—capture the return value, and treat any return value greater than or equal to the buffer size as truncation. For security-critical strings such as paths or commands, reject the operation rather than proceeding with truncated data.
How snprintf bounds a write
snprintf is defined in C99 and retained in C11, C17, and C23. It writes at most size - 1 characters plus a null terminator into the destination buffer, so it never writes beyond size bytes. The return value is the number of characters that would have been written if the buffer had been large enough, excluding the null terminator.
That distinction matters. If the return value is less than size, the entire formatted string fit. If it is greater than or equal to size, output was truncated and the buffer contains only a prefix, still null-terminated.
Worked example: building a log path safely
The following function formats a log-file path from a hostname and date. It returns zero on success, a negative code on encoding error, and a distinct code when truncation occurs.
#include <stdio.h>
#include <stddef.h>
enum log_path_status {
LOG_PATH_OK = 0,
LOG_PATH_ENCODING_ERROR = -1,
LOG_PATH_TRUNCATED = -2
};
int build_log_path(char *dest, size_t dest_size,
const char *hostname, const char *date)
{
int needed = snprintf(dest, dest_size,
"/var/log/app/%s/%s.log",
hostname, date);
if (needed < 0) {
return LOG_PATH_ENCODING_ERROR;
}
if ((size_t)needed >= dest_size) {
return LOG_PATH_TRUNCATED;
}
return LOG_PATH_OK;
}
Call it with the real array, not a pointer:
char path[64];
int status = build_log_path(path, sizeof(path), "server01", "2026-12-03");
if (status == LOG_PATH_TRUNCATED) {
/* The hostname or date was too long. Do not use path. */
return -1;
}
Why sizeof(buffer) matters
Array parameters decay to pointers inside a function. If you write snprintf(buf, sizeof(buf), ...) where buf is a function parameter declared as char buf[256], sizeof(buf) yields the pointer size—typically 8 bytes on a 64-bit system—not 256. snprintf then writes into only 8 bytes, and any longer string truncates immediately.
Pass the size from the caller, where the array has not decayed, or store the size in a separate variable.
Limits and common mistakes
- Ignoring the return value. Without checking it, you cannot tell whether
pathholds the full string or a truncated prefix. Security-critical strings must fail closed. - Using sizeof on a pointer. As shown above, this shrinks the effective bound and causes premature truncation.
- Passing zero as size. This is allowed:
snprintfwrites nothing and returns the would-be length. Do not use it to probe buffer capacity; it writes nothing to the destination. - Overlapping source and destination. If the format string or an argument overlaps the output buffer, behavior is undefined.
- Assuming truncation is harmless. A truncated command or path can resolve to an unintended file or execute the wrong operation.
Practical verification
Compile with strict C99 and warnings enabled:
gcc -std=c99 -Wall -Wextra -o snprintf_check snprintf_check.c
Run under AddressSanitizer to confirm no writes escape the destination array when output exceeds the buffer:
gcc -std=c99 -Wall -Wextra -fsanitize=address -o snprintf_check_asan snprintf_check.c
./snprintf_check_asan
Where to run: a normal development terminal. No special permissions are required. Placeholders: replace snprintf_check.c with your source file name. Expected check: the program exits with the truncation status when the buffer is too small, and AddressSanitizer reports no heap or stack buffer overflow. Risk: AddressSanitizer increases binary size and runtime overhead; use it for testing, not production builds.
To confirm C99 availability, check the macro:
#if __STDC_VERSION__ < 199901L
#error "snprintf requires C99 or later"
#endif
Limitations
The return value is type int. On systems where formatted output could exceed INT_MAX, the return value is not a reliable size measurement; this is rare for typical path or message buffers but worth noting for very large output. snprintf also does not tell you how much larger the buffer must be beyond the truncation fact; you must choose a new size and retry, or dynamically allocate based on the returned length plus one for the null terminator.
Practical way to check the result
Add a temporary diagnostic print in a test build:
fprintf(stderr, "needed=%d size=%zu truncation=%d\n",
needed, dest_size, needed >= 0 && (size_t)needed >= dest_size);
Run the test with inputs that intentionally exceed the buffer. Confirm the program reports truncation and does not use the truncated string. Remove or guard the diagnostic before production.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.