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

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

问题描述

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

<块引用>

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

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

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

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

解决方案

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

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

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

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

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

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

(.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.

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

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

解决方案

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.

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

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

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

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天全站免登陆