雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

Linux系統(tǒng)下C語言gets函數(shù)出現(xiàn)警告問題的解決方法

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊:

發(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,問題解決。

總結

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

上一篇:在C++中關于友元函數(shù)的進一步理解

欄    目:C語言

下一篇:C語言中getchar()的返回類型為什么是int詳解

本文標題:Linux系統(tǒng)下C語言gets函數(shù)出現(xiàn)警告問題的解決方法

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/647.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權所有