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

发现问题

最近在Linux下编译C语言,用到gets这个函数,代码如下:

#include

#include

#include

void main(){

char s[100]; // 存放输入的字符串

int i, j, n;

printf("输入字符串:");

gets(s);

n=strlen(s);

for(i=0,j=n-1;i

if(s[i]!=s[j]) break;

if(i>=j)

printf("是回文串\n");

else

printf("不是回文串\n");

}

6a94b81114c92d812fa3d9450328d823.png

但是出现如下警告,

[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.

5a83bcd151cfce4c5daaf24ab7aae494.png

问题解决

原因就在于,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

#include

#include

void main(){

char s[100]; // 存放输入的字符串

int i, j, n;

printf("输入字符串:");

scanf("%[^\n]",s); //改成这个就OK

n=strlen(s);

for(i=0,j=n-1;i

if(s[i]!=s[j]) break;

if(i>=j)

printf("是回文串\n");

else

printf("不是回文串\n");

}

4c94b2d1ab6e9d30c0234fd1963870eb.png

OK,问题解决。

总结

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

时间: 2018-12-04

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值