gpt4 book ai didi

c - 使用 get 防止缓冲区溢出

转载 作者:行者123 更新时间:2023-11-30 17:11:50 26 4
gpt4 key购买 nike

gets的声明是:

char * gets ( char * str );

请注意明显遗漏str的最大尺寸。

cplusplus.com 2 :

Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).

还有:

The most recent revision of the C standard (2011) has definitively removed this function from its specification. The function is deprecated in C++ (as of 2011 standard, which follows C99+TC3).

现在,当然,fgets通常建议替代 gets ,因为它的声明如下所示:

char * fgets ( char * str, int num, FILE * stream );

确实采用尺寸参数。这使得它比gets安全得多。 。

现在因为我不愿意花钱下载或购买 C11 standard ,任何人都可以解释一下弃用的原因 gets这对 future 的代码意味着什么?为什么fgets时它存在于同一个地方?更安全吗?为什么它直到现在才被弃用?

最佳答案

gets 已被弃用,因为它不安全,正如您已经引用的那样,它可能会导致缓冲区溢出。为了进行替换,C11 提供了一个替代的 gets_s ,其签名如下:

char *gets_s(char *s, rsize_t n);

请注意,C11 仍然建议使用 fgets 来替换 gets

是否将 gets 放入标准中一开始就存在争议,但委员会认为,当程序员确实对输入有足够的控制时,gets 很有用。

这是委员会的官方解释。

Rationale for International Standard - Programming Languages C §7.19.7.7 The gets function:

Because gets does not check for buffer overrun, it is generally unsafe to use when its input is not under the programmer’s control. This has caused some to question whether it should appear in the Standard at all. The Committee decided that gets was useful and convenient in those special circumstances when the programmer does have adequate control over the input, and as longstanding existing practice, it needed a standard specification. In general, however, the preferred function is fgets (see §7.19.7.2).

关于c - 使用 get 防止缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31953960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com