面试中如问到 memcpy 的实现,那就要小心了,这里有陷阱。
先看下标准 memcpy()的解释:
void *memcpy(void *dst, const void *src, size_t n);//If copying takes place between objects that
overlap, the behavior is undefined.
注意下面的注释,对于地址重叠的情况,该函数的行为是未定义的。
事实上所说的陷阱也在于此,自己动手实现 memcpy()时就需要考虑地址重叠的情况。
另外,标准库也提供了地址重叠时的内存拷贝函数:memmove() ,那么为什么还要考虑重写
memcpy()函数呢?
因为 memmove() 函数的实现效率问题,该函数把源字符串拷贝到临时 buf 里,然后再从临
时 buf里写到目的地址,增加了一次不必要的开销。
下面给出 memcpy()的实现,为了与标准库函数区分,我们实现其包裹函数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *Memcpy(void *dst, const void *src, size_t size);
int main(int argc, char *argv[])
{
char buf[100] = "abcdefghijk";
//memcpy(buf+2, buf, 5);
Memcpy(buf+2, buf, 5);
printf("%s", buf+2);
}
void *Memcpy(void *dst, const void *src, size_t size)
{
char *psrc;
char *pdst;
if(NULL == dst || NULL == src)
{
return NULL;
}
if((src < dst) && (char *)src + size > (char *)dst) //自后向前拷贝
{
psrc = (char *)src + size - 1;
pdst = (char *)dst + size - 1;
while(size--)
{
*pdst-- = *psrc--;
}
}
else
{
psrc = (char *)src;
pdst = (char *)dst;
while(size--)