MEMCPY(3) BSD Library Functions Manual MEMCPY(3)
NAME
memcpy -- copy memory areaLIBRARY
Standard C Library (libc, -lc)SYNOPSIS
#include <string.h>void *
memcpy(void *restrict dst, const void *restrict src, size_t n);DESCRIPTION
The memcpy() function copies n bytes from memory area src to memory area
dst. If dst and src overlap, behavior is undefined. Applications in
which dst and src might overlap should use memmove(3) instead.RETURN VALUES
The memcpy() function returns the original value of dst.
另外,标准库也提供了地址重叠时的内存拷贝函数:memmove(),那么为什么还要考虑重写memcpy()函数呢?因为memmove()函数的实现效率问题,该函数把源字符串拷贝到临时buf里,然后再从临时buf里写到目的地址,增加了一次不必要的开销。
可以看到memcpy对于地址重叠(overlap)是未定义的
所以我们可以实现一个memcpy函数
#include <iostream>
using namespace std;
void *Memcpy(void *dst,const void *src,size_t size)
{
char *pdst=(char *)dst;
char *psrc=(char *)src;
if(dst==NULL || src==NULL)
return NULL;
//如果src和dst有重叠,则从后往前进行复制
if((src<dst) && (char *)src+size>(char *)dst)
{
pdst=(char *)dst+size-1;
psrc=(char *)src+size-1;
while(size--)
{
*pdst--=*psrc--;
}
}
else//否则正常复制就好了
{
pdst=(char *)dst;
psrc=(char *)src;
while(size--)
{
*pdst++=*psrc++;
}
}
return dst;
}
int main()
{
char buff[100]="abcdefghijk";
Memcpy(buff+2, buff, 5);
cout<<buff<<endl;
}
结果:
ababcdehijk