C/C++ 中的 gets 与 fgets 问题
条评论在 PTA拼题 提交代码时碰到的一点坑!!
在处理 解析字符串 类型问题的时候, 经常需要读入包含 空格 的长字符串, 在C语言中, 最初通常使用 gets
函数来读取包含空格的字符串, 但是在 C/C++11 中已被摒弃.
官方参考手册 给出以下解释:
Notes
The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard.fgets()
andgets_s()
are the recommended replacements.
具体会出现怎样的错误呢:
1 | int main() { |
如果程序输入 1234
, 那么得到的输出显然是 1234
, 这没问题.
现在继续新的输入 12345678
, 同样可以得到相同的输出 12345678
.
但是, 如果输入内容继续加大, 比如 12345678901234567890
, 此时会得到这样一个输出:
1 | warning: this program uses gets(), which is unsafe. |
可以看到, 输入的字符串还是被原样输出了, 但是同时伴有一条 segmentation fault (段错误) 的信息被输出.
困了, 待续…..
1 |
|
- 本文链接:https://blog.charjin.top/2019/07/10/c-cpp-gets-fgets/
- 版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 CN 许可协议。转载请注明出处!
分享