memcpy的原型:
SYNOPSIS
#include <string.h> void *memcpy(void *dest, const void *src, size_t n); DESCRIPTION
The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove() if
the memory areas do overlap. RETURN VALUE
The memcpy() function returns a pointer to dest.
实现时要注意:
1. 空指针的情况。
2. dest和src是否内存重叠。
void* memcpy2(void* dest, void* src, size_t n) {
if (dest == NULL || src == NULL) return NULL;
char* pa = (char*)dest, *pb = (char*)src;
if (pa <= pb) {
while (n--) {
*pa++ = *pb++;
}
} else {
pa += n - ;
pb += n - ;
while (n--) {
*pa-- = *pb--;
}
}
return dest;
}
因为,都是假设dest和src都是有足够的n个空间。所以有两种情况:
dest在src前面,有重叠;这时可以从头往尾拷贝,不会污染到数据;
dest在src后面,有重叠;这时可以从尾往头拷贝;
没有重叠的情况下,两种方向的拷贝都是安全的。