1. 程式人生 > >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");
}

Linux C語言gets函數出現的警告問題解決

但是出現如下警告,

Linux C語言gets函數出現的警告問題解決

  原因就在於,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");
}

Linux C語言gets函數出現的警告問題解決

OK,問題解決。