Linux系統(tǒng)下C語言gets函數(shù)出現(xiàn)警告問題的解決方法
發(fā)現(xiàn)問題
最近在Linux下編譯C語言,用到gets這個函數(shù),代碼如下:
#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"); }
但是出現(xiàn)如下警告,
[linuxidc@localhost linuxidc.com]$ gcc linuxidc.c -o linuxidc.com
linuxidc.c: 在函數(shù)‘main'中:
linuxidc.c:8:5: 警告:不建議使用‘gets'(聲明于 /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(s);
^
/tmp/ccvwVatT.o:在函數(shù)‘main'中:
linuxidc.c:(.text+0x1f): 警告:the `gets' function is dangerous and should not be used.
問題解決
原因就在于,gets不會去檢查字符串的長度,如果字符串過長就會導致溢出。如果溢出的字符覆蓋了其他一些重要數(shù)據(jù)就會導致不可預測的后果。在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的掃描集來實現(xiàn)這一功能,只要在方括號中寫入“^\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,問題解決。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
C++:構(gòu)造函數(shù),析構(gòu)函數(shù)詳解
今天小編就為大家分享一篇關于C++構(gòu)造函數(shù)和析構(gòu)函數(shù)的文章,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2021-09-09C++實現(xiàn)LeetCode(108.將有序數(shù)組轉(zhuǎn)為二叉搜索樹)
這篇文章主要介紹了C++實現(xiàn)LeetCode(108.將有序數(shù)組轉(zhuǎn)為二叉搜索樹),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07C++從文本文件讀取數(shù)據(jù)到vector中的方法
這篇文章主要給大家介紹了利用C++如何從文本文件讀取數(shù)據(jù)到vector中,文章通過實例給出示例代碼,相信會對大家的理解和學習很有幫助,有需要的朋友們下面來一起看看吧。2016-10-10C語言中fgetgrent()函數(shù)和fgetpwent()函數(shù)的用法對比
這篇文章主要介紹了C語言中fgetgrent()函數(shù)和fgetpwent()函數(shù)的用法對比,分別用于讀取組格式函數(shù)和讀取密碼格式,需要的朋友可以參考下2015-08-08