1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > warning: the `gets' function is dangerous and should not be used.

warning: the `gets' function is dangerous and should not be used.

时间:2022-02-11 01:11:06

相关推荐

warning: the `gets' function is dangerous and should not be used.

问题

今天在LINUX下编译C程序时,出现了

main.c:29:5: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration]gets(buffer);

warning: the `gets' function is dangerous and should not be used.

这个warning。

原因

问题出在程序中使用了 gets是非常不安全的

这是对程序产生BUG,出现不可靠性的一个描述,有些函数在某些意外情况会导致程序陷入不可控状态,仅仅是PC上运行最多也就是退出而已,但是如果是运行在飞机等系统里的话,就会有大麻烦,说危险也不为过。因为英文文献里描述为dangerous,所以也就翻译为危险。

函数执行需要一个栈空间,但这个栈空间容量是有限的,而且栈里存放了函数返回的地址。gets()函数在获取输入时,如果无限输入会造成栈空间溢出,在程序返回时,不能正常的找到返回地址,程序将发生不可预测行为

解决

解决办法是使用 fgets

fgets()函数的基本用法为:

fgets(char * s,int size,FILE * stream);//eg:可以用fgets(tempstr,10,stdin)//tempstr 为char[]变量,10为要输入的字符串长度,stdin为从标准终端输入。

示例程序

/* 代码实现*/#include <stdio.h>int main ( ) {char name[20];printf("\n 输入任意字符 : ");fgets(name, 20, stdin);//stdin 意思是键盘输入fputs(name, stdout); //stdout 输出return 0;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。