basics · intermediate · ~15 min

Bounded string copy

Replace the unsafe strcpy with a length-aware copy.

Challenge

Copy a string into a fixed-size buffer without ever overflowing it — the safe alternative to strcpy.

Task

Implement int bounded_copy(char *dst, int dstsz, const char *src) that copies at most dstsz-1 bytes from src into dst, then always writes a terminating NUL. Return the number of bytes copied (excluding the NUL). If dstsz is 0 there is no room even for the terminator, so copy nothing and return -1. No main — the grader calls it.

Input

A destination buffer dst, its capacity int dstsz, and a NUL-terminated source src.

Output

Returns the count of bytes copied (excluding the NUL), or -1 when dstsz is 0.

Example

bounded_copy(dst[8], 8, "hello")   ->   5,   dst == "hello"
bounded_copy(dst[4], 4, "hello")   ->   3,   dst == "hel"   (truncated)
bounded_copy(dst,    0, "x")       ->   -1                 (no room)

Edge cases

  • dstsz == 0 returns -1 and writes nothing.
  • When src is longer than the buffer, it is truncated and dst is still NUL-terminated.

Rules

  • Reserve one byte for the '\0' — that's exactly what strcpy fails to do.

Input format

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

Output format

Bytes copied excluding the NUL, or -1 when dstsz is 0.

Constraints

Copy at most dstsz-1 bytes; always NUL-terminate; dstsz==0 returns -1.

Starter code

int bounded_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.