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,问题解决。

猜你喜欢

转载自www.linuxidc.com/Linux/2018-12/155699.htm