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
If these two strings overlap, then, while copying you'll run over the original a
or b
pointers.
Assuming that strcpy( a, b ) roughly means a <- b, i.e., the first parameter is the destination of the copy, then you only check whether the copy pointer reaches b
's position.
You only need to save the b
original position, and while copying, check you haven't reached it. Also, don't write the trailing zero if you have reached that position.
char* my_strcpy(char *a, const char *b)
{
if ( a == NULL
|| b == NULL )
{
return NULL;
}
char *n = a;
const char * oldB = b;
while( *b != '\0'
&& a != oldB )
{
*a = *b;
a++;
b++;
}
if ( a != oldB ) {
*a = '\0';
}
return n;
}
This algorithm just stops copying. Maybe you want to do something else, such as marking the error condition, or add an end-of-the string mark to the previous position (though failing silently (as the algorithm does at the moment) isn't the best option).
Hope this helps.