pointers-memory · intermediate · ~15 min

Implement strcpy

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

Challenge

Write your own strcpy: copy a C string, including its NUL terminator, into a destination buffer.

Task

Implement char *my_strcpy(char *dst, const char *src) that copies src (including the terminating \0) into dst and returns dst. No main — the grader calls it.

Input

  • dst: a writable buffer large enough to hold src plus its terminator.
  • src: a NUL-terminated source string (may be empty).

Output

Returns dst. After the call dst contains a byte-for-byte copy of src including the NUL.

Example

my_strcpy(buf, "hello")   ->   buf = "hello", returns buf
my_strcpy(buf, "")        ->   buf = ""

Edge cases

  • Empty source copies just the NUL byte.
  • The returned pointer must equal the original dst.

Rules

  • 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.

Input format

A writable buffer dst and a NUL-terminated source src.

Output format

dst (the original pointer); dst now holds a copy of src including the NUL.

Constraints

Do not call the standard strcpy; dst must be large enough.

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.