凡是涉及cpy函数感觉都要考虑内存重叠问题,并且在重叠情况下考虑是前重叠 还是后重叠的情况来选择*dest++=*source++ 还是 *dest--=*source--来进行内存复制。
写一个简单的memcpy关于内存覆盖的源码:
void * memcpy(void * dest, void * source,size_t count)
{
if(dest==NULL||source==NULL)
{
return NULL;
}
else
{
char * tmp_source,* tmp_dest;
tmp_source=(char *)source;
tmp_dest=(char *)dest;//if the pointer is string we must check the length of two string.
if(dest + count >= source || source + count >= dest)//there are two kind of memory overlap
{
if(dest + count >= source)//dest is front of the source overlap
{
while(count--)
{
*tmp_dest++=*tmp_source++;
}
}
else//dest is behind of the source overlap
{
tmp_dest+=count-1;
tmp_source+=count-1;
while(count--)
{
*tmp_dest--=*tmp_source--;
}
}
}
else//no overlap
{
while(count--)
{
*tmp_dest++=*tmp_source++;// *tmp_dest--=*tmp_source-- is also right
}
}
}
return(dest);//why return the pointer?? , it can nest use and if overlap we can creat new space to receive this pointer
}