博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
memcpy内存拷贝及优化策略图解
阅读量:7028 次
发布时间:2019-06-28

本文共 811 字,大约阅读时间需要 2 分钟。

一般内存拷贝与优化

代码实现

#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\n",p1);

    printf("%s\n",p2);

    

    h_memcpy(p1, p2, 2);

    printf("%s\n",p2);

    

    return 0;

}

你可能感兴趣的文章
理解webpack原理,手写一个100行的webpack
查看>>
Node.js & Express 项目基本搭建
查看>>
掌握 MySQL 这 19 个骚操作,效率至少提高3倍
查看>>
【跃迁之路】【744天】程序员高效学习方法论探索系列(实验阶段501-2019.3.6)...
查看>>
用于大数据测试、学习的测试数据
查看>>
Software System Analysis and Design | 1
查看>>
JavaScript函数式编程,真香之组合(一)
查看>>
JavaScript链式调用实例浅析
查看>>
报表没完没了怎么办? | 润乾集算器提效报表开发
查看>>
记一次Hexo迁移
查看>>
RESTful API 中的 Status code 是否要遵守规范
查看>>
第十一天-《企业应用架构模式》-对象-关系行为模式
查看>>
[spring boot] jdbc
查看>>
新的开始!
查看>>
区块链— 比特币中的区块、账户验证和记账
查看>>
Electron打包,NSIS修改默认安装路径
查看>>
分享一些好用的网站
查看>>
【Android】Retrofit 2.0 的使用
查看>>
Nacos系列:基于Nacos的注册中心
查看>>
原生JS 实现复杂对象深拷贝(对象值包含函数)
查看>>