basics · intermediate · ~15 min

Bounded string copy

Replace the unsafe strcpy with a length-aware copy.

Challenge

Implement int bounded_copy(char *dst, int dstsz, const char *src) that copies at most dstsz-1 bytes from src, always NUL-terminates, and returns the number of bytes copied (excluding the NUL). If dstsz is 0, copy nothing and return -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.