pointers-memory · intermediate · ~12 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

Transfer exercise: apply the lesson to a complete function contract.

Input format

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

Output format

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

Constraints

Non-NULL live src/dst, terminated src, disjoint regions; dst has strlen(src)+1 writable bytes. Borrow both; return original dst. Do not use library strcpy.

Starter code

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

Common mistakes

Losing the original destination pointer or omitting the terminator.

Edge cases to handle

Empty source still copies its terminator; preserve bytes after the copied string.

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.