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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对呐喊教程的支持。