memcpy 内存重叠问题

凡是涉及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
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值