• strcpy函数的实现


    http://blog.csdn.net/gpengtao/article/details/7464061

    大家一般认为名不见经传strcpy函数实现不是很难,流行的strcpy函数写法是:

    [cpp] view plaincopy
     
    1. char *my_strcpy(char *dst,const char *src)  
    2. {  
    3.     assert(dst != NULL);  
    4.     assert(src != NULL);  
    5.     char *ret = dst;  
    6.     while((* dst++ = * src++) != '')   
    7.         ;  
    8.     return ret;  
    9. }  

    如果注意到:

    1,检查指针有效性;

    2,返回目的指针des;

    3,源字符串的末尾 '' 需要拷贝。

    写出上面实现函数就不在话下。

    然而这样的实现没有考虑拷贝时内存重叠的情况,下面的测试用例就能使调用my_strcp函数的程序崩溃:

    [cpp] view plaincopy
     
    1. char str[10]="abc";  
    2. my_strcpy(str+1,str);  


    然而调用系统的strcpy函数程序正常运行,打印str结果为“aabc”!可见系统strcpy函数的实现不是这样的。

    strcpy的正确实现应为:

    [cpp] view plaincopy
     
    1. char *my_strcpy(char *dst,const char *src)  
    2. {  
    3.     assert(dst != NULL);  
    4.     assert(src != NULL);  
    5.     char *ret = dst;  
    6.     memcpy(dst,src,strlen(src)+1);  
    7.     return ret;  
    8. }  

    memcpy函数实现时考虑到了内存重叠的情况,可以完成指定大小的内存拷贝,它的实现方式建议查看文章“卓越的教练是如何训练高手的?”,会获益良多,这里仅粘帖函数memcpy函数的实现:

    [cpp] view plaincopy
     
    1. void * my_memcpy(void *dst,const void *src,unsigned int count)  
    2. {  
    3.      assert(dst);  
    4.      assert(src);  
    5.      void * ret = dst;  
    6.      if (dst <= src || (char *)dst >= ((char *)src + count))//源地址和目的地址不重叠,低字节向高字节拷贝  
    7.      {  
    8.          while(count--)  
    9.          {  
    10.              *(char *)dst = *(char *)src;  
    11.              dst = (char *)dst + 1;  
    12.              src = (char *)src + 1;  
    13.          }  
    14.      }  
    15.      else                       //源地址和目的地址重叠,高字节向低字节拷贝  
    16.      {   
    17.          dst = (char *)dst + count - 1;  
    18.          src = (char *)src + count - 1;   
    19.          while(count--)   
    20.          {  
    21.              *(char *)dst = *(char *)src;  
    22.              dst = (char *)dst - 1;  
    23.              src = (char *)src - 1;  
    24.          }  
    25.     }  
    26.     return ret;  
    27. }  

    两者结合才是strcpy函数的真正实现吧。

  • 相关阅读:
    发布MeteoInfo 1.2.4
    发布MeteoInfo 1.2.3
    FY2E HDF格式数据处理绘图
    格点插值为站点数据批量处理
    Linux安装make无法使用
    sql语句优化
    在OSX狮子(Lion)上安装MYSQL(Install MySQL on Mac OSX)
    JetBrains IntelliJ IDEA for Mac 15.0 破解版 – Mac 上强大的 Java 集成开发工具
    Spring-data-redis: 分布式队列
    Spring Boot使用Redis进行消息的发布订阅
  • 原文地址:https://www.cnblogs.com/johnnyflute/p/3747478.html
Copyright © 2020-2023  润新知