cybersecurity · intermediate · ~15 min

Fix the sprintf overflow

`snprintf` semantics and how to detect truncation.

Challenge

Replace an unsafe sprintf with snprintf and detect truncation.

Task

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.

Input

  • out / out_sz: the destination buffer and its size in bytes.
  • name: a NUL-terminated name string.
  • score: an integer score.

Output

Returns 0 on success, or -1 if the formatted result would not fit (truncation). The buffer is always NUL-terminated when out_sz > 0.

Example

format_user(buf, 32, "ada", 100)            ->   0, buf = "ada: 100"
format_user(buf, 8, "verylongname", 100)    ->   -1   (truncated)

Edge cases

  • If the result would be truncated, return -1 and still NUL-terminate.

Rules

  • Use snprintf and check its return value: a value >= out_sz means truncation.

Input format

Destination out with size out_sz, a name string, and an int score.

Output format

0 on success, -1 if truncated; out is NUL-terminated when out_sz > 0.

Constraints

Use snprintf and treat a return value >= out_sz as truncation.

Starter code

#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.