memcpy和memmove的区别

tech2022-07-11  212

memmove在copy两个有重叠区域的内存时可以保证copy的正确,但是memcpy就不可以保证有重叠区域的拷贝是正确的。

memcpy的源码

void *memcpy(void *dest, const void *src, size_t count) { assert(dest != NULL || src != NULL); char *tmp = (char *)dest; char *p = (char *)src; while (count--) { *tmp++ = *p++; } return dest; }

memmove的源码

/** * 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; }

对比源码,我们可以发现memmove有内存重叠处理,即选择从前开始进行赋值还是从后开始进行赋值,这个取决于dst和src的区间开始位置。

最新回复(0)