开发者

warning:gets function is dangerous [duplicate]

开发者 https://www.devze.com 2022-12-30 05:03 出处:网络
This question already has answers here: Why is the gets function so dangerous that it should not be used?
This question already has answers here: Why is the gets function so dangerous that it should not be used? 开发者_如何转开发 (13 answers) Closed 8 years ago.

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?


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.


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.


Buffer overruns are dangerous. Here's the definition:

/* Get a line from the stdin stream. */
char *gets(char *buffer);

How big is the buffer? If a user types more data that can fit in the buffer, the program could crash and be susceptible to hacker exploits.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消