memmove对比memcpy差异

结论

void *memmove(void *str1, const void *str2, size_t n)str2 复制 n 个字符到 str1,但是在重叠内存块这方面,memmove() 是比 memcpy() 更安全的方法。如果目标区域和源区域有重叠的话,memmove() 能够保证源串在被覆盖之前将重叠区域的字节拷贝到目标区域中,复制后源区域的内容会被更改。如果目标区域与源区域没有重叠,则和 memcpy() 函数功能相同。

函数声明

/* Copy N bytes of SRC to DEST.  */
extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
		     size_t __n) __THROW __nonnull ((1, 2));
/* Copy N bytes of SRC to DEST, guaranteeing
   correct behavior for overlapping strings.  */
extern void *memmove (void *__dest, const void *__src, size_t __n)
     __THROW __nonnull ((1, 2));

memmove的源码实现

void *memmove(void *__dest, const void *__src, size_t count) {
    unsigned char *      d = __dest;
    const unsigned char *s = __src;

    if (__src == __dest)
        return __dest;

    if (__dest < __src)
        return memcpy(__dest, __src, count);

    while (count--)
        d[count] = s[count];
    
    return __dest;
}

memcpy的源码实现

void *memcpy(void *__dest, __const void *__src, size_t __n) {
    int            i = 0;
    unsigned char *d = ( unsigned char * )__dest, *s = ( unsigned char * )__src;

    for (i = __n >> 3; i > 0; i--) {
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
    }

    if (__n & 1 << 2) {
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
    }

    if (__n & 1 << 1) {
        *d++ = *s++;
        *d++ = *s++;
    }

    if (__n & 1)
        *d++ = *s++;

    return __dest;
}
posted @ 2021-11-21 12:15  flxx  阅读(108)  评论(0编辑  收藏  举报