碼海拾遺:strcpy()、strncpy()和strcpy_s()區別


  1、strcpy()

  原型:char *strcpy(char *dst,const char *src)

  功能:將以src為首地址的字符串復制到以dst為首地址的字符串,包括'\0'結束符,返回dst地址。要求:src和dst所指內存區域不可以重疊且dst必須有足夠的空間來容納src的字符串,若dst空間不足,編譯時並不會報錯,但執行時因系統不同會出現不同的結果:Mac系統提示“Abort trap:6”(Mac);CentOS7系統會正常運行(可能是個例,可以正常運行)

  測試代碼:

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main(int argc,char* argv[])
 5 {
 6     char buf[2];
 7     char *str = "hello world";
 8 
 9     strcpy(buf,str);
10     printf("buf:%s\nsizeof(buf) = %ld\nstrlen(buf) = %ld\n",
11            buf,sizeof(buf),strlen(buf));
12 
13     return 0;
14 }
View Code

 

  2、strncpy()

  原型:char *strncpy(char *dst,const char *src,size_t len)

  功能:從以src為首地址的字符串中之多復制len個字符到以dst為首地址的字符串。如果在[0,len]之間沒有'\0'結束符,則dst中沒有結束符。

  如果len大於src的長度,則dst中多余位置自動置為null

  測試代碼:  

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main(int argc,char* argv[])
 5 {
 6     char buf[20];
 7     char *str = "hello world";
 8 
 9     strncpy(buf,str,20);
10     printf("buf:%s\nsizeof(buf) = %ld\nstrlen(buf) = %ld\n",
11            buf,sizeof(buf),strlen(buf));
12 
13     return 0;
14 }
View Code

  如果len小於src的長度,則dst中沒有結束符,dst輸出時會出現亂碼,直至碰到'\0'結束符為止。

  測試代碼:

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main(int argc,char* argv[])
 5 {
 6     char buf[4];
 7     char *str = "hello world";
 8 
 9     strncpy(buf,str,5);
10     printf("buf:%s\nsizeof(buf) = %ld\nstrlen(buf) = %ld\n",
11            buf,sizeof(buf),strlen(buf));
12 
13     return 0;
14 }
View Code

   3、strcpy_s()

  該函數是VS2005之后的VS提供的,並非C標准函數

  原型:strcpy_s( char *dst,   size_t num,   const char *src )

  功能:同strcpy()函數功能相同,不同之處在於參數中多了個size_t類型的參數,該參數為字符串dst的長度,當存在緩存區溢出的問題時(即src的長度大於dst的長度),strcpy_s()會拋出異常;而strcpy()結果則未定,因為它錯誤地改變了程序中其他部分的內存的數據,可能不會拋出異常但導致程序數據錯誤,也可能由於非法內存訪問拋出異常。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM