C语言 -- 考虑内存覆盖情况下的memcpy函数的模拟实现

模拟实现memcpy时的内存覆盖问题

发现问题

如果不考虑内存覆盖问题,将会出现以下情况:

//不考虑内存覆盖问题模拟实现memcpy
void* my_memcpy(void* destination, const void* source, size_t num)
{
	assert(destination != NULL && source != NULL);
	char* pdest = (char*)destination;
	const char* psour = (const char*)source;

	while (num--)
	{
		*pdest++ = *psour++;
	}

	return destination;
}

void main()
{
	char str[10] = "012345678";
	char* pstr = my_memcpy(str+2,str,4); //本意是得到010123678
	printf("%s\n", str); //结果得到010101678
}

上述代码所出现的情况,主要原因如下:

对于同一个字符串来说,source所指向的位置在destination的前面,并且需要拷贝(替换)的内容包含了destination指向及指向之后的内容,所以当开始拷贝的时候,destination所指向的空间内容已经被覆盖掉,这也就造成所得到的结果和预期的不大一样。

问题解决

处理方法如下:

void* my_memcpy(void* destination, const void* source, size_t num)
{
	assert(destination != NULL && source != NULL);
	char* pdest = (char*)destination;
	const char* psour = (const char*)source;

	//对于可能会出现内存覆盖的情况作以判断
	if (psour < pdest && (psour + num) > pdest)
	{
		pdest = pdest + num - 1;
		psour = psour + num - 1;
		while (num-->0)
		{
			*pdest-- = *psour--;
		}
	}
	else 
	{
		while (num-->0)
		{
			*pdest++ = *psour++;
		}
	}
	return destination;
}

void main()
{
	char str[10] = "012345678";
	char* pstr = my_memcpy(str + 2, str, 4); //本意是得到010123678
	printf("%s\n", str); //结果正确得到010123678
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值