warning:gets function is dangerous [duplicate]

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?


Solution 1:

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.

Solution 2:

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.

Solution 3:

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.

Solution 4:

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.