zoukankan      html  css  js  c++  java
  • c中gets函数使用可能导致缓冲区溢出

    头文件:#include <stdio.h>

    gets()函数用于从缓冲区中读取字符串,其原型如下:
        char *gets(char *string);

    gets()函数从流中读取字符串,直到出现换行符或读到文件尾为止,最后加上NULL作为字符串结束。所读取的字符串暂存在给定的参数string中。

    【返回值】若成功则返回string的指针,否则返回NULL。

    注意:由于gets()不检查字符串string的大小,必须遇到换行符或文件结尾才会结束输入,因此容易造成缓存溢出的安全性问题,导致程序崩溃,可以使用fgets()代替。

    【实例】请看下面一个简单的例子。

    1. #include <stdio.h>
    2. int main(void)
    3. {
    4. char str[10];
    5. printf("Input a string. ");
    6. gets(str);
    7. printf("The string you input is: %s",str); //输出所有的值,注意a
    8. }

    如果输入123456(长度小于10),则输出结果为:
    Input a string.
    123456↙
    The string you input is:123456

    如果输入12345678901234567890(长度大于10),则输出结果为:
    Input a string.
    12345678901234567890↙
    The string you input is:12345678901234567890
    同时看到系统提示程序已经崩溃。

    如果不能正确使用gets()函数,带来的危害是很大的,就如上面我们看到的,输入字符串的长度大于缓冲区长度时,并没有截断,原样输出了读入的字符串,造成程序崩溃。

    考虑到程序安全性和健壮性,建议用fgets()来代替gets()。

    如果你在GCC中使用gets(),编译无法通过,会提示:
    the 'gets' function is dangerous and shout not be used.

  • 相关阅读:
    [APIO 2009] Atm
    Codeforces518 D. Ilya and Escalator
    [POJ2096] Collecting bugs
    [ZOJ3329] One Person Game
    [LightOJ1038] Race to 1 Again
    「NOI2003」逃学的小孩
    [HAOI2006] 旅行
    ☆ [POJ2411] Mondriaan's Dream 「状压DP」
    「POJ3311」Hie with the Pie
    「乘法逆元」 学习笔记
  • 原文地址:https://www.cnblogs.com/bonelee/p/6149543.html
Copyright © 2011-2022 走看看