Google Interview Question
Software Engineer in Testsvoid* memcpy(void *src, void *dst,int len){
if (src == NULL || dst == NULL || len <= 0) return NULL ;
if (src - dst < len) { //Overlap
src = src + len ;
dst = dst + len ;
while(len--)
*dst-- = *src-- ;
}
else { // No overlap
while(len--)
*dst++ = *src++ ;
}
return dst ;
}
The overlap thing isn't correct, because adding len to both src and dst, it still preserves the condition (dst - src < len), which will result in overlap again. Get rid of the src = src + len line, and just make the while loop like in the case of no overlap.
Yes you are right Anonymous.
@Azza the code should be
void* memcpy(void *src, void *dst,int len)
{
if (src == NULL || dst == NULL || len <= 0) return NULL ;
if (dst - src < len)
{ //Overlap
dst = dst + len ;
}
while(len--)
*dst++ = *src++ ;
return dst ;
}
One more question: can we copy void* type memory? I guess we have to convert to char* type. Please comment.
why not
- chris November 07, 2012if src < dst
copy from end to beginning;
else
copy from beginning to end