zoukankan      html  css  js  c++  java
  • memcpy内存拷贝及优化策略图解


    一般内存拷贝与优化





    代码实现


    #include<iostream>

    usingnamespace std;

     

    //不安全的内存拷贝(当源内存地址与目标内存地址重叠时会产生错误)

    void h_memcpy(void*src,void *dst,intsize){

        if (src == NULL|| dst == NULL) {

           return;

        }

        

        const char *s =(char *)src;

        char *d = (char*)dst;

        

        while (size--) {

           *d++ = *s++;

        }

    }

     

    //内存移动(安全的内存拷贝,措施为依据源内存地址和目的内存地址不同使用不同的拷贝顺序)

    void h_memmove(void*src,void *dst,intsize){

        if (src == NULL|| dst == NULL) {

           return;

        }

        

        const char *s =(char *)src;

        char *d = (char*)dst;

     

        if (s > d) {

           while (size--) {

               *d++ = *s++;

           }

        }elseif(s < d){      // 正向反向拷贝的目的就是为了避免未移动内存被覆盖

           d = d + size -1;

           s = s +size - 1;

           while (size--) {

               *d-- = *s--;

           }

        }

        // s == d, you should do nothing!~

    }

     

     

    int main(intargc,const char* argv[])

    {

        char s[] = "12345";

        char *p1 = s;

        char *p2 = s+2;

        printf("%s ",p1);

        printf("%s ",p2);

        

        h_memcpy(p1, p2, 2);

        printf("%s ",p2);

        

        return 0;

    }


  • 相关阅读:
    聊天工具分享bug
    Git命令查看代码提交次数
    短链接生成实例
    .Net MVC用户注册验证码
    js写验证码
    笔记
    jq获取数组中的某个字段拆分成字符串。
    IIS部署后中文Cookie乱码
    C#反射(Reflection)与特性(Attribute)实例
    jmm
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4029773.html
Copyright © 2011-2022 走看看