Linux C语言gets函数出现的警告问题解决

栏目: C · 发布时间: 7年前

内容简介:在Linux下编译C语言,用到gets这个函数,代码如下:#include <stdio.h>#include <string.h>

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函数出现的警告问题解决

但是出现如下警告,

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

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

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

本文永久更新链接地址: https://www.linuxidc.com/Linux/2018-12/155699.htm


以上所述就是小编给大家介绍的《Linux C语言gets函数出现的警告问题解决》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

挑战编程

挑战编程

斯基纳 / 刘汝佳 / 2009-7 / 39.00元

《挑战编程:程序设计竞赛训练手册》分为14章,分别介绍在线评测系统的基本使用方法、数据结构、字符串、排序、算术与代数、组合数学、数论、回溯法、图遍历、图算法、动态规划、网格、几何,以及计算几何,并在附录中介绍了一些著名的程序设计竞赛以及相应的备赛建议与比赛技巧。每章的正文用十余页的篇幅覆盖了该领域最核心的概念和算法,然后给出八道可在线提交的完整编程挑战题目供读者练习。 全书内容紧凑、信息量大......一起来看看 《挑战编程》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具