问题来源于《 c与指针》 1.7章节中的一个问题:
问题:下面的代码可能出现什么问题?
while ( gets (input) != NULL){}
首先我粗略的分析了一下,这行语句不就是输入一个字符串吗。 “!= NULL” 表示如果输入成功了,就继续运行。没想出来什么问题,于是决定在机器上面编译一下。于是写了代码如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char * input = NULL;
while (gets(input) != NULL){
puts(input);
}
return EXIT_SUCCESS;
}
编译运行结果如下:
[root@localhost program]# gcc -g pgetsDemo.c -o pgetsDemo
/tmp/cc0OMzQL.o: In function `main':
/program/pgetsDemo.c:6: warning: the `gets' function is dangerous and should not be used.
[root@localhost program]# ./pgetsDemo
hello
Segmentation fault
寻找解决办法途中得知:现在linux下使用fgets函数代替了gets函数,原因:
安全性问题