Linux系统下C语言gets函数出现警告问题的解决方法

时间:2021-05-20

发现问题

最近在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");elseprintf("不是回文串\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); //改成这个就OKn=strlen(s);for(i=0,j=n-1;i<j;i++,j--)if(s[i]!=s[j]) break;if(i>=j)printf("是回文串\n");elseprintf("不是回文串\n");}


OK,问题解决。

总结

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章