Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / C语言字符串拷贝strcpy函数的陷阱分析

在C语言中,我们都知道字符串是永恒的话题,字符串含有很多地雷,你稍不留心就会被砸到,比方说,字符串的结尾是"",也是占一个字符空间的,那么如果我们在利用strcpy拷贝字符串的时候,应该多加1个字符空间,就是专门留给这个""的。如果我们不多加一个字符空间,会发生致命的错误,那么我们通过案例来说明。将C语言梳理一下,分布在以下10个章节中:
  1. Linux-C成长之路(一):Linux下C编程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成长之路(二):基本数据类型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成长之路(三):基本IO函数操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成长之路(四):运算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成长之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成长之路(六):函数要义 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成长之路(七):数组与指针 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成长之路(八):存储类,动态内存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成长之路(九):复合数据类型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成长之路(十):其他高级议题
C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码 http://www.linuxidc.com/Linux/2014-05/101227.htmC++11中正则表达式测试 http://www.linuxidc.com/Linux/2012-08/69086.htm-------------我是分割线------------------# include <stdio.h># include <stdlib.h># include <string.h> int main(){    char str[] = "MengLiang";    //此处分配空间没有考虑到""    char* New_str = (char*)malloc(strlen(str));       strcpy(New_str, str);       printf("The New_str = %s ", New_str);     free(New_str);    New_str = NULL;       system("pause");    return 0;}
-------------我是分割线------------------
我在注释中已经写了,那么这小段程序的结果呢? -------------我是分割线------------------正确的修改为:-------------我是分割线------------------# include <stdio.h># include <stdlib.h># include <string.h> int main(){    char str[] = "MengLiang";    //此处的加1就是为""来服务的    char* New_str = (char*)malloc(strlen(str)+1);       strcpy(New_str, str);       printf("The New_str = %s ", New_str);       free(New_str);    New_str = NULL;       system("pause");    return 0;}
-------------我是分割线------------------C语言的自由意味着我们要自制!----------------------------------------------本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-06/102589.htm