pointers-memory · intermediate · ~15 min

Implement strcpy

Practise pointer assignment with the canonical idiom `while ((*d++ = *s++));`

Challenge

Implement char *my_strcpy(char *dst, const char *src) copying the null terminator too, and returning dst. Do not call the standard strcpy.

Why this matters

Writing your own strcpy gives a visceral understanding of why the function is unsafe by default — there's no destination size argument, just a faith-based copy.

Starter code

char *my_strcpy(char *dst, const char *src) {
    /* TODO */
    return dst;
}

Common mistakes

Forgetting to copy the trailing NUL (now dst isn't a valid C string). Mutating the source. Returning the wrong pointer (strcpy returns dst).

Edge cases to handle

Empty source ("") — still copies the NUL. Source equals destination — undefined (use memmove).

Complexity

O(strlen(src)).

Background lessons

Up next

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