实现memcpy
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(3) if the memory areas do overlap. RETURN VALUE The memcpy() function returns a pointer to dest.
实现时要注意:
1. 空指针的情况。
2. dest和src是否内存重叠。
1 void* memcpy2(void* dest, void* src, size_t n) { 2 if (dest == NULL || src == NULL) return NULL; 3 char* pa = (char*)dest, *pb = (char*)src; 4 if (pa <= pb) { 5 while (n--) { 6 *pa++ = *pb++; 7 } 8 } else { 9 pa += n - 1; 10 pb += n - 1; 11 while (n--) { 12 *pa-- = *pb--; 13 } 14 } 15 return dest; 16 }
因为,都是假设dest和src都是有足够的n个空间。所以有两种情况:
dest在src前面,有重叠;这时可以从头往尾拷贝,不会污染到数据;
dest在src后面,有重叠;这时可以从尾往头拷贝;
没有重叠的情况下,两种方向的拷贝都是安全的。