cybersecurity · intermediate · ~15 min

strlcpy-style copy

Replace strcpy with a size-aware copy.

Challenge

Write a size-aware string copy that never overflows the destination and reports truncation — the safe replacement for strcpy.

Task

Implement int safe_copy(char *dst, int dstsz, const char *src) that copies at most dstsz - 1 bytes of src into dst, always NUL-terminates dst, and returns 0 if all of src fit or -1 if it was truncated. Return -1 if dstsz <= 0.

Input

  • dst: the destination buffer.
  • dstsz: the size of dst in bytes.
  • src: a NUL-terminated source string.

Output

Returns 0 if the whole string fit, -1 if it was truncated (or dstsz <= 0). dst is always NUL-terminated when dstsz > 0.

Example

safe_copy(buf, 8, "hello")   ->   0,  buf = "hello"
safe_copy(buf, 4, "hello")   ->   -1, buf = "hel"   (truncated)

Edge cases

  • dstsz <= 0: return -1, write nothing.
  • A string that fits exactly: return 0.

Rules

  • Never write past dstsz; always NUL-terminate; signal truncation via the return value.

Input format

A destination dst, its size dstsz, and a NUL-terminated src.

Output format

0 if all of src fit, -1 if truncated or dstsz <= 0; dst always NUL-terminated when dstsz > 0.

Constraints

Copy at most dstsz-1 bytes; always NUL-terminate; report truncation.

Starter code

int safe_copy(char *dst, int dstsz, const char *src) {
    /* TODO */
    return -1;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.