In an interview, I was asked to write an implementation of strcpy and then fix it so that it properly handles overlapping strings. My implementation is below and it is very naiv
This SO entry is already older, but I am currently working on a old piece of code that copies overlapping strings with strcpy()
. Characters were missing in the log output. I decided to use the following compact solution, which copies char
by char
.
static char *overlapped_strcpy(char *dest, const char *src)
{
char *dst = dest;
if (dest == NULL || src == NULL || dest == src)
return dest;
do {
*dst++ = *src;
} while (*src++);
return dest;
}
EDIT:
As @Gerhardh pointed out, the code above only works if dest <= src
(I just had to solve this case). For the case dest > src
it is more complicated. However, copying from behind, as other answers have already mentioned, leads to success. For example:
if (dest <= src) {
/* do the above */
} else {
int i = (int)strlen(src);
while (i >= 0) {
dst[i] = src[i];
i--;
}
}