Implement strcpy
Implement char *my_strcpy(char *dst, const char *src) that copies the string src, including the terminating '\0', into dst and returns dst. Assume dst is large enough.
Then be ready to explain why strcpy is considered dangerous and what to use instead.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Copy one character at a time and stop after you have copied the '\0'. Save the original dst first, because you will move the pointer.
#include <stdio.h>
#include <string.h>
char *my_strcpy(char *dst, const char *src)
{
char *ret = dst;
while ((*dst++ = *src++) != '\0')
; /* copy includes the '\0' */
return ret;
}
Your version is correct: the assignment inside the condition copies the character first, then tests it, so the terminator is copied before the loop stops. The shorter form above is the classic K&R idiom.
Walk-through: "hi"
| step | copied | value tested | continue? |
|---|---|---|---|
| 1 | dst[0] = 'h' | 'h' | yes |
| 2 | dst[1] = 'i' | 'i' | yes |
| 3 | dst[2] = '\0' | '\0' | no → return original dst |
Why strcpy is dangerous: it has no idea how big dst is. If src is longer, it writes past the end of the buffer, a buffer overflow that corrupts the stack or heap and is a classic security hole. MISRA C and CERT C forbid it with untrusted input.
Safer alternatives:
- snprintf(dst, size, "%s", src): always terminates, returns the length it wanted to write.
- strlcpy (BSD, glibc 2.38+, POSIX 2024): always terminates, reports truncation (see Safe String Copy).
- Not strncpy: it does not terminate dst when src is too long, and it pads the rest with zeros.
Other follow-ups: overlapping src and dst are undefined behaviour; strcpy returns dst so calls can be chained, but that means you cannot easily get the end position (POSIX stpcpy returns a pointer to the new terminator, useful for appending).
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
char d[32];
memset(d, 'X', sizeof d);
CHECK(my_strcpy(d, "firmware") == d && strcmp(d, "firmware") == 0);
CHECK(d[8] == '\0' && d[9] == 'X'); /* terminator copied, nothing after it */
CHECK(my_strcpy(d, "") == d && d[0] == '\0');
char e[8];
CHECK(strcmp(my_strcpy(e, "abc"), "abc") == 0); /* return value is usable */
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}