【问题标题】:Why is fgets() considered in gcc(linux) and what is the alternative to use it? [duplicate]为什么在 gcc(linux) 中考虑 fgets() 以及使用它的替代方法是什么? [复制]
【发布时间】:2011-10-09 07:23:54
【问题描述】:

可能重复:
Why is the `gets' function is dangerous? Why should not be used?

我建议用户使用 fgets() 输入字符串,该字符串将使用 scanf() 进行分析以区分整数、浮点数和字符。我想要一个可靠的程序,但我使用 gcc 收到以下警告:

在函数main': : warning: thegets'函数是危险的,不应该使用。

谁能告诉我为什么它很危险,什么是安全的替代品? 如果有人能告诉我 fgets() 的严重性,那将非常有帮助。

【问题讨论】:

标签: c linux gcc stdio fgets


【解决方案1】:

你可能有点困惑。简而言之:gets 不好,fgets 很好。

man 页面解释了为什么不应使用 gets

BUGS
       Never use gets().  Because it is impossible to tell without knowing the
       data  in  advance  how  many  characters  gets() will read, and because
       gets() will continue to store characters past the end of the buffer, it
       is  extremely  dangerous  to  use.   It has been used to break computer
       security.  Use fgets() instead.

fgets 将缓冲区的大小作为其参数之一,如果使用正确,则不会出现此问题。

FAQ 有一个entry with more details

【讨论】:

  • fgets() 也显示了此警告
  • @jatt.beas 我对此表示怀疑。
  • @jatt.beas:我的gcc 不会抱怨fgets(即使是-Wall)。向我们展示代码并告诉我们编译器的版本。
  • @aix 对不起,我只使用了 gets(),只是我的错误
  • @aix 对不起,我也浪费了你的时间
猜你喜欢
  • 2022-01-31
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多