warning:gets function is dangerous [duplicate]

2019-01-02 21:24发布

This question already has an answer here:

When i use gets function,gcc gives me a warning:

warning:the `gets' function is dangerous and should not be used.

Why gets and puts function dangerous?

标签: c
7条回答
还给你的自由
2楼-- · 2019-01-02 21:31

If you have code like this:

char s[10];
gets( s );

and you type in more than 10 characters when the program is run, you will overflow the buffer, causing undefined behaviour. The gets() function has no means of preventing you typing the characters and so should be avoided. Instead you should use fgets(), which allows you to limit the number of characters read, so that the buffer does not overflow.:

char s[10];
fgets( s, 10, stdin );

The puts() function is perfectly safe, provided the string that you are outputting is null-terminated.

查看更多
何处买醉
3楼-- · 2019-01-02 21:31

Gets does not check for buffer overrun exposing your code to attack

查看更多
低头抚发
4楼-- · 2019-01-02 21:36

gets reads data into the given area of memory until a newline or end of file is encountered. If the input (e.g. as supplied by the user) contains a line longer than the size of the buffer supplied to gets, it will overflow and gets will write to memory outside the buffer. At worst this may allow a malicious user to write data that alters the behaviour of the program or possibly even executes arbitrary code with the privileges of that program (e.g. one that may be running on a remote server or with the privileges of another user), and even accidental overflows are likely to break the software.

fgets should be used instead, as it takes an additional argument to constrain the size of the input.

查看更多
初与友歌
6楼-- · 2019-01-02 21:47

As Wikipedia's article says, gets() is inherently unsafe because all it takes is a char * as the argument.

This is dangerous because there is no way for the method to know how much space has been allocated to that char * in any situation. Therefore gets behaves as if it has a blank check to write as much data to it as possible, which could result in buffer overruns.

The alternative is fgets which takes in not just the character array, but the maximum length and the stream pointer. gets is kept around only for backwards compatibility with older code.

查看更多
荒废的爱情
7楼-- · 2019-01-02 21:52

Because gets doesn't constrain the amount of data it reads, and is thus vulnerable to buffer overruns. @Neil's answer has the appropriate solution to this.

The puts function isn't dangerous, AFAIK, unless, of course, you forget to null-terminate it.

查看更多
登录 后发表回答