• 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;
    }
    
  • 相关阅读:
    14-快速排序
    linux上挂在windows的共享文件系统,大小写不敏感
    【mount】linux挂共享盘
    监控windows服务或者进程
    自定义时间间隔
    示例
    filebeat
    kafka
    文档碎片
    简单DOM操作
  • 原文地址:https://www.cnblogs.com/faithlocus/p/15584040.html
Copyright © 2020-2023  润新知