为什么gets函数如此危险以至于不应该使用它? [英] Why is the gets function so dangerous that it should not be used?

查看:17
本文介绍了为什么gets函数如此危险以至于不应该使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过 GCC 编译使用 gets() 函数的 C 代码时,我收到以下警告:

When I try to compile C code that uses the gets() function with GCC, I get this warning:

(.text+0x34):警告:`gets' 函数很危险,不应使用.

(.text+0x34): warning: the `gets' function is dangerous and should not be used.

我记得这与堆栈保护和安全性有关,但我不确定具体原因.

I remember this has something to do with stack protection and security, but I'm not sure exactly why.

我怎样才能删除这个警告?为什么会有关于使用 gets() 的警告?

How can I remove this warning and why is there such a warning about using gets()?

如果 gets() 如此危险,那我们为什么不能删除它呢?

If gets() is so dangerous then why can't we remove it?

推荐答案

为了安全地使用 gets,你必须准确地知道你将要读多少个字符,这样你才能使你的缓冲区足够大.只有确切知道要读取哪些数据,您才会知道这一点.

In order to use gets safely, you have to know exactly how many characters you will be reading, so that you can make your buffer large enough. You will only know that if you know exactly what data you will be reading.

您想使用 getsrel="nofollow noreferrer">fgets,有签名

Instead of using gets, you want to use fgets, which has the signature

char* fgets(char *string, int length, FILE * stream);

(fgets,如果它读取整行,会将 ' ' 留在字符串中;你必须处理它.)

(fgets, if it reads an entire line, will leave the ' ' in the string; you'll have to deal with that.)

gets 直到 1999 年 ISO C 标准仍然是该语言的官方部分,但在 2011 标准.大多数 C 实现仍然支持它,但至少 gcc 会针对任何使用它的代码发出警告.

gets remained an official part of the language up to the 1999 ISO C standard, but it was officially removed in the 2011 standard. Most C implementations still support it, but at least gcc issues a warning for any code that uses it.

这篇关于为什么gets函数如此危险以至于不应该使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆