basics · intermediate · ~15 min
Replace the unsafe strcpy with a length-aware copy.
Copy a string into a fixed-size buffer without ever overflowing it — the safe alternative to strcpy.
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.
A destination buffer dst, its capacity int dstsz, and a NUL-terminated source src.
Returns the count of bytes copied (excluding the NUL), or -1 when dstsz is 0.
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)
dstsz == 0 returns -1 and writes nothing.src is longer than the buffer, it is truncated and dst is still NUL-terminated.'\0' — that's exactly what strcpy fails to do.A destination dst, its capacity int dstsz, and a NUL-terminated src.
Bytes copied excluding the NUL, or -1 when dstsz is 0.
Copy at most dstsz-1 bytes; always NUL-terminate; dstsz==0 returns -1.
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.