memcpy() memmove()函数的区别和实现

原型

void * memmove ( void * destination, const void * source, size_t num );
void * memcpy ( void * destination, const void * source, size_t num );

功能

memcpy与memmove的目的都是将N个字节的源内存地址的内容拷贝到目标内存地址中。
但当源内存和目标内存存在重叠时,memcpy会出现错误,而memmove能正确地实施拷贝,但这也增加了一点点开销。

memmove的处理措施:(移动内存)

  1. 当源内存的首地址等于目标内存的首地址时,不进行任何拷贝
  2. 当源内存的首地址大于目标内存的首地址时,实行正向拷贝
  3. 当源内存的首地址小于目标内存的首地址时,实行反向拷贝

示意图

(1)内存低端 <-----s-----> <-----d-----> 内存高端 start at end of s
(2)内存低端 <-----s–<==>–d-----> 内存高端 start at end of s

(3)内存低端 <-----sd-----> 内存高端 do nothing

(4)内存低端 <-----d–<==>–s-----> 内存高端 start at beginning of s
(5)内存低端 <-----d-----> <-----s-----> 内存高端 start at beginning of s

实现

#include <iostream>
#include <vector>
#include <stack>
#include <string>

using namespace std;
class Solution {
public:
	//移动内存
	void* memcpy(void* dest, const void* src, size_t n);
	void* memmove(void* dest, const void* src, size_t n);
};

int main()
{
	Solution sol;
	char str1[20] = "hello world";
	char str2[40], str3[40];

	sol.memcpy(str2, str1, sizeof(str1) / sizeof(str1[0]));
	sol.memmove(str3, str1, sizeof(str1) / sizeof(str1[0]));

	cout << str2 << endl << str3;
	cout << endl;
	system("pause");
	return 0;
}

//无需考虑内存重叠问题
void * Solution::memcpy(void * dest, const void * src, size_t n)
{
	char* d = (char*)dest;
	const char* s = (const char*) src;
	while (n--)
	{
		*d++ = *s++;
	}
	return dest;
}

void * Solution::memmove(void * dest, const void * src, size_t n)
{
	char* d = (char*)dest;
	const char* s = (const char*)src;

	if (s > d)//源地址在后,从前往后
	{
		while (n--)
			*d++ = *s++;
	}
	if (s < d)//源地址在前,从后往前
	{
		d = d + n - 1;
		s = s + n - 1;
		while (n--)
		{
			*d-- = *s--;
		}
	}
	return dest;
}

猜你喜欢

转载自blog.csdn.net/vict_wang/article/details/85794096
今日推荐