歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言字符串拷貝strcpy函數的陷阱分析

C語言字符串拷貝strcpy函數的陷阱分析

日期:2017/3/1 9:43:40   编辑:Linux編程

在C語言中,我們都知道字符串是永恆的話題,字符串含有很多地雷,你稍不留心就會被砸到,比方說,字符串的結尾是'\0',也是占一個字符空間的,那麼如果我們在利用strcpy拷貝字符串的時候,應該多加1個字符空間,就是專門留給這個'\0'的。

如果我們不多加一個字符空間,會發生致命的錯誤,那麼我們通過案例來說明。

將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.htm

C++11中正則表達式測試 http://www.linuxidc.com/Linux/2012-08/69086.htm

-------------我是分割線------------------

# include <stdio.h>

# include <stdlib.h>

# include <string.h>

int main()

{

char str[] = "MengLiang";

//此處分配空間沒有考慮到'\0'

char* New_str = (char*)malloc(strlen(str));

strcpy(New_str, str);

printf("The New_str = %s\n", 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就是為'\0'來服務的

char* New_str = (char*)malloc(strlen(str)+1);

strcpy(New_str, str);

printf("The New_str = %s\n", New_str);

free(New_str);

New_str = NULL;

system("pause");

return 0;

}


-------------我是分割線------------------

C語言的自由意味著我們要自制!

----------------------------------------------

Copyright © Linux教程網 All Rights Reserved