判断overlapping 条件如下:
If ( (dest <= src) || // green region 1
(dest >=src+count) ) // green region 2
{
// no memory overlapping
}
Else // red region 3
{
// there is overlapping
}
Overlapping 的处理:
我们可以看到memcpy_no_handle_overlap 函数,是从低地址依次赋值到高地址;在处理overlapping 时,如果我们采用同样的方法( 低地址到高地址) ,高地址的值将会被覆盖,所以我们应该从高地址依次到低地址赋值,如下图:
函数代码如下:
void *memcpy_handle_overlap(void *dest, void *src, unsigned int count)
{
if ((NULL==dest) || (NULL==src))
return NULL;
char *d = (char *)dest;
char *s = (char *)src;
//Check for overlapping buffers:
if ( (d<=s) || (d>=s+count) )
{
//Do normal (Upwards) Copy
while (count-- > 0)
*d++ = *s++;
}
else
{
//Do Downwards Copy to avoid propagation
while (count > 0)
{
*(d+count-1) = *(s+count-1);
--count;
}
}
return dest;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hzgdiyer/archive/2011/01/25/6163767.aspx
我想说的是memcpy怎么会产生覆盖问题,,因为你的des地址是由malloc产生的,是在堆上,,而src地址是在栈上。。即使src也是malloc的,那么系统调用malloc申请des地址的话也不会和src覆盖的。。