cybersecurity · intermediate · ~15 min
`snprintf` semantics and how to detect truncation.
Replace an unsafe sprintf with snprintf and detect truncation.
Implement int format_user(char *out, size_t out_sz, const char *name, int score) that writes "<name>: <score>" into out using bounded formatting. No main — the grader calls it.
out / out_sz: the destination buffer and its size in bytes.name: a NUL-terminated name string.score: an integer score.Returns 0 on success, or -1 if the formatted result would not fit (truncation). The buffer is always NUL-terminated when out_sz > 0.
format_user(buf, 32, "ada", 100) -> 0, buf = "ada: 100"
format_user(buf, 8, "verylongname", 100) -> -1 (truncated)
-1 and still NUL-terminate.snprintf and check its return value: a value >= out_sz means truncation.Destination out with size out_sz, a name string, and an int score.
0 on success, -1 if truncated; out is NUL-terminated when out_sz > 0.
Use snprintf and treat a return value >= out_sz as truncation.
#include <stdio.h>
#include <stddef.h>
int format_user(char *out, size_t out_sz, const char *name, int score) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.