Step 6 of 7
Safe formatting with snprintf
sprintf(buf, ...) writes as much as the format produces, overflowing buf if it's too small. That exact bug has caused countless security holes. snprintf takes the buffer size and never writes past it:
char buf[16];
int needed = snprintf(buf, sizeof buf, "%s scored %d", name, score);
if (needed < 0 || (size_t)needed >= sizeof buf) {
/* output was truncated (or an encoding error happened) */
}
Its return value is the length the full output would have had, so comparing it with the buffer size tells you whether anything was cut off. The result is always '\0'-terminated (for a nonzero size).
Your turn: write int format_kd(char *buf, size_t size, const char *name, int kills, int deaths) that writes NAME K/D (like ropz 25/12). Return 0 if it fit, -1 if it was truncated.