当我尝试用GCC编译使用gets()函数的C代码时,我得到这个警告:
(.text+0x34):警告:' gets'函数是危险的,不应该使用。
我记得这与堆栈保护和安全性有关,但我不确定确切的原因。
我如何删除这个警告,为什么使用gets()会有这样的警告?
如果gets()是如此危险,那么为什么我们不能删除它?
当我尝试用GCC编译使用gets()函数的C代码时,我得到这个警告:
(.text+0x34):警告:' gets'函数是危险的,不应该使用。
我记得这与堆栈保护和安全性有关,但我不确定确切的原因。
我如何删除这个警告,为什么使用gets()会有这样的警告?
如果gets()是如此危险,那么为什么我们不能删除它?
当前回答
简单地说,gets() (can)是危险的,因为用户可能会输入比变量有足够空间存储的内容更大的内容。第一个答案是关于fgets()以及为什么它更安全。
其他回答
简单地说,gets() (can)是危险的,因为用户可能会输入比变量有足够空间存储的内容更大的内容。第一个答案是关于fgets()以及为什么它更安全。
gets() is dangerous because it is possible for the user to crash the program by typing too much into the prompt. It can't detect the end of available memory, so if you allocate an amount of memory too small for the purpose, it can cause a seg fault and crash. Sometimes it seems very unlikely that a user will type 1000 letters into a prompt meant for a person's name, but as programmers, we need to make our programs bulletproof. (it may also be a security risk if a user can crash a system program by sending too much data).
Fgets()允许您指定从标准输入缓冲区中取出多少字符,以便它们不会溢出变量。
为了安全地使用get,您必须确切地知道将要读取多少字符,以便使缓冲区足够大。只有当您确切地知道要读取哪些数据时,您才会知道这一点。
您希望使用具有签名的fgets,而不是使用gets
char* fgets(char *string, int length, FILE * stream);
(fgets,如果它读取了整行,将在字符串中留下'\n';你得自己处理。)
直到1999年的ISO C标准,gets仍然是语言的官方部分,但在2011年的标准中被正式删除。大多数C实现仍然支持它,但至少gcc会对任何使用它的代码发出警告。
我最近在comp.lang.c的一篇USENET文章中读到,gets()将从标准中删除。哦吼
你会很高兴知道 委员会刚刚投票(一致通过) 将gets()从 还有草案。
fgets。
从stdin读取:
char string[512];
fgets(string, sizeof(string), stdin); /* no buffer overflows here, you're safe! */