Prevent buffer overflows with gets [duplicate]

纵然是瞬间 提交于 2019-11-28 13:52:06

gets is deprecated because it's unsafe, as what you already quoted, it may cause buffer overflow. For replacement, C11 provides an alternative gets_s with a signature like this:

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

Note that C11 still recommends fgets to replace gets.

Whether putting gets in the standard is controversial in the first place, but the Committee decided that gets was useful when the programmer does have adequate control over the input.

Here's the official explanation by the Committee.

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

Now since I'm not willing to shell out money to download or buy the C11 standard, can anyone shed some light on the reason for deprecating gets and what it means for future code?

From C committee in C99 Rationale:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!