Linux系統下C語言gets函數出現警告問題的解決方法

這篇文章主要給大家介紹了關於在Linux系統下C語言gets函數出現警告問題的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

發現問題

最近在Linux下編譯C語言,用到gets這個函數,代碼如下:

#include <stdio.h>

#include <string.h>

#include <string.h>

void main(){

char s[100]; // 存放輸入的字符串

int i, j, n;

printf("輸入字符串:");

gets(s);

n=strlen(s);

for(i=0,j=n-1;i<j;i++,j--)

if(s[i]!=s[j]) break;

if(i>=j)

printf("是迴文串\n");

else

printf("不是迴文串\n");

}


但是出現如下警告,

[linuxidc@localhost linuxidc.com]$ gcc linuxidc.c -o linuxidc.com

linuxidc.c: 在函數‘main'中:

linuxidc.c:8:5: 警告:不建議使用‘gets'(聲明於 /usr/include/stdio.h:638) [-Wdeprecated-declarations]

gets(s);

^

/tmp/ccvwVatT.o:在函數‘main'中:

linuxidc.c:(.text+0x1f): 警告:the `gets' function is dangerous and should not be used.


問題解決

原因就在於,gets不會去檢查字符串的長度,如果字符串過長就會導致溢出。如果溢出的字符覆蓋了其他一些重要數據就會導致不可預測的後果。在man手冊裏也有關於gets這樣的警告:

Never use gets().  Because it is impossible to tell without knowing the data in advance how many  characters  gets()  will  read,  and  because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use.  It has  been  used  to  break  computer security.

可以用scanf的掃描集來實現這一功能,只要在方括號中寫入“^\n”,即:直到輸入了回車才停止掃描。下面來演示這一用法:

#include <stdio.h>

#include <string.h>

#include <string.h>

void main(){

char s[100]; // 存放輸入的字符串

int i, j, n;

printf("輸入字符串:");

scanf("%[^\n]",s); //改成這個就OK

n=strlen(s);

for(i=0,j=n-1;i<j;i++,j--)

if(s[i]!=s[j]) break;

if(i>=j)

printf("是迴文串\n");

else

printf("不是迴文串\n");

}


OK,問題解決。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對神馬文庫的支持。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章