As well answered by others concerning returning the original dest as below,
char *ft_strcpy(char *dest, char *src) {
char *original_dest = dest; // add
while (*src) {
*dest++ = *src++;
}
*dest = '\0';
// return dest;
return original_dest;
}
It is interesting to think about the impact of overlapping strings. The below will cause ft_strcpy() to loop on and on until code accesses outside buf[] leading to undefined behavior rather than a hoped for "hehello". The while (*src) { loop, in this case, over wrote the null character.
char buf[10] = "hello";
ft_strcpy(buf + 2, buf);
Such calls as above are pathological, yet allowed.
The standard strcpy() disallows this type of call with restrict. Simplistically, this means s1,s2 shall not overlap.
char *strcpy(char * restrict s1, const char * restrict s2);
How could code be written to handle overlapping strings?
Determine the length before copying.
Copy with memmove() which handles overlapping buffers.
char *ft_strcpy2(char *dest, const char *src) {
size_t sz = strlen(src) + 1;
memmove(dest, src, sz);
return dest;
}
int main(void) {
char buf[10] = "hello";
puts(ft_strcpy2(buf + 2, buf));
puts(buf);
}
Output
hello
hehello