1.strcpy函式
原型宣告:char strcpy(char dest, const char *src);
頭檔案:#include <string.h> 和 #include <stdio.h>
功能:把從src地址開始且含有NULL結束符的字串復制到以dest開始的地址空間
說明:src和dest所指記憶體區域不可以重疊且dest必須有足夠的空間來容納src的字串,
隱患說明:當src的長度大于dest分配到的空間,就會出現記憶體溢位
應當使用strncpy,而避免使用strcpy
2.sscanf函式
int sscanf (const char *str,const char * format,…);
sscanf()會將引數str的字串根據引數format字串來轉換并格式化數 據,格式轉換形式請參考scanf(),轉換后的結果存于對應的引數內,
回傳值 成功則回傳引數數目,失敗則回傳-1,錯誤原因存于errno中, 回傳0表示失敗 否則,表示正確格式化資料的個數
當format用到%s或者%[]等要注意記憶體溢位
char array[10] = {0};
隱患寫法: scanf("%s", array);
最優寫法: scanf("%9s", array);
隱患寫法: scanf("%[]", array);
最優寫法: scanf("%9[]", array);
3.sprintf函式
函式功能:格式化字串,將格式化的資料寫入字串中,
函式原型:int sprintf(char *buffer, const char *format, [argument]…)
引數:
(1)buffer:是char型別的指標,指向寫入的字串指標;
(2)format:格式化字串,即在程式中想要的格式;
(3)argument:可選引數,可以為任意型別的資料;
函式回傳值:buffer指向的字串的長度;
sprintf(array, "Hello World!");
當 "Hello World!"的資料長度比array的記憶體空間大,則會導致記憶體溢位
應當盡量使用snprintf,避免使用sprintf
4.strncmp函式
strncmp是不會造成記憶體溢位的,但是有可能比較長度存在隱患
隱患寫法:strncmp(array,"helloworld",strlen("helloworld"));
當array[]="helloworldhelloworld",對比也能通過
最優寫法1:strncmp(array,"helloworld",strlen("helloworld")+1);
最優寫法2:strcmp(array,"helloworld");
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277117.html
標籤:其他
下一篇:金毛獅王煞費苦心取屠龍刀
