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
I was asked this in a recent interview. We don't have to 'detect' overlap. We can write strcpy
in such a way that overlapping addresses are taken care of. The key is to copy from the end of source string instead of from the start.
Here is a quick code.
void str_copy(const char *src, char *dst)
{
/* error checks */
int i = strlen(a); /* may have to account for null character */
while(i >= 0)
{
dst[i] = src[i];
i--;
}
}
EDIT: This only works when a < b. For a > b, copy from the start.