首页 > 其他 > 详细

memcpy内存拷贝及优化策略图解

时间:2014-10-16 22:13:54      阅读:369      评论:0      收藏:0      [点我收藏+]


一般内存拷贝与优化


bubuko.com,布布扣

bubuko.com,布布扣


代码实现


#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;

}


memcpy内存拷贝及优化策略图解

原文:http://www.cnblogs.com/bhlsheji/p/4029773.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!