【注】改编自memmove 和 memcpy的区别。原做者若有不爽,请告知!html
memcpy是C语言中的库函数,在头文件string.h中,做用是拷贝必定长度的内存的内容,原型分别以下:linux
void *memcpy(void *dest, const void *src, size_t count)
使用memcpy时,有可能会遇到内存重叠的问题:
第一种状况下,拷贝重叠的区域不会出现问题,内容都可以正确的被拷贝。
第二种状况下,问题出如今右边的两个字节,这两个字节的原来的内容首先就被覆盖了,并且没有保存。因此接下来拷贝的时候,拷贝的是已经被覆盖的内容,显然这是有问题的。git
经过memmove能够避免这一问题。memmove和memcpy实现同样的功能:内存拷贝。原型以下:github
void *memmove(void *dest, const void *src, size_t count)
如下几点你须要了解:app
有兴趣的,能够看看linux的源码,实现很简单,一看就明白。函数
/** * memcpy - Copy one area of memory to another * @dest: Where to copy to * @src: Where to copy from * @count: The size of the area. * * You should not use this function to access IO space, use memcpy_toio() * or memcpy_fromio() instead. */ void *memcpy(void *dest, const void *src, size_t count) { char *tmp = dest; const char *s = src; while (count--) *tmp++ = *s++; return dest; } /** * memmove - Copy one area of memory to another * @dest: Where to copy to * @src: Where to copy from * @count: The size of the area. * * Unlike memcpy(), memmove() copes with overlapping areas. */ void *memmove(void *dest, const void *src, size_t count) { char *tmp; const char *s; if (dest <= src) { tmp = dest; s = src; while (count--) *tmp++ = *s++; } else { tmp = dest; tmp += count; s = src; s += count; while (count--) *--tmp = *--s; } return dest; }