cybersecurity · intermediate · ~15 min
Replace strcpy with a size-aware copy.
Write a size-aware string copy that never overflows the destination and reports truncation — the safe replacement for strcpy.
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.
dst: the destination buffer.dstsz: the size of dst in bytes.src: a NUL-terminated source string.Returns 0 if the whole string fit, -1 if it was truncated (or dstsz <= 0). dst is always NUL-terminated when dstsz > 0.
safe_copy(buf, 8, "hello") -> 0, buf = "hello"
safe_copy(buf, 4, "hello") -> -1, buf = "hel" (truncated)
dstsz <= 0: return -1, write nothing.dstsz; always NUL-terminate; signal truncation via the return value.A destination dst, its size dstsz, and a NUL-terminated src.
0 if all of src fit, -1 if truncated or dstsz <= 0; dst always NUL-terminated when dstsz > 0.
Copy at most dstsz-1 bytes; always NUL-terminate; report truncation.
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.