简书链接:c语言gets为什么是不安全的输入
文章字数:378,阅读全文大约需要1分钟
getsscalef一样可以接收用户输入,但是gets能修改一个地址,而且get是不安全的,xcode就会提示警告信息warning: this program uses gets(), which is unsafe.

1
代码如下

int main(int args,const char* argv[]){
char a[]=”good”;
char b[3];
printf(“please input strs:\n”);
gets(b);
printf(“you input content %s,a str=%s\n”,b,a);
return 5;
}

1
在限定b字符串只有3个元素的情况下,输入的内容超过3个,而且当a的字符串也不是很长的情况下,bug,出现,输入了 hell,结果是 a变量的前两位被分别篡改为```l```,以及```\0```

please input strs:
warning: this program uses gets(), which is unsafe.
hell
you input content hell,a str=l
Program ended with exit code: 5

1
这个bug在a字符串很长的时候看不出来.但是我们也可以输入很长,这样会把程序也搞崩溃,全改成了字符串.

int main(int args,const char* argv[]){
char a[]=”goodfffffffff”;
char b[3];
printf(“please input strs:\n”);
gets(b);
printf(“you input content %s,a str=%s\n”,b,a);
printf(“\na address %#x,b address %#x\n”,a,b);
return 5;
}

![image.png](https://upload-images.jianshu.io/upload_images/2815884-8d1cb16498a7b70d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

这里还有一个知识点就是 堆是递增,而栈是递减,所以这里 的地址越往下 地址反而越小。