Google

Wednesday, March 19, 2008

Dont use the function gets( )

Never, never, NEVER use the function gets(). It is the most dangerous function in the entire C standard library because there is there is no way to use it safely!
Consider this example:

int main(void)
{
char name [25];
printf("Enter your name: ");
fflush(stdout);
if (gets(name) != NULL)
printf("Hello %s\n", name);
return 0;
}

What will happen if the user types fifty characters into twenty-five character array?
The answer is that gets() will fill up array and then keep on going, trying to write to memory past the end of the array which the program does not have the right to access. A program crash is likely.


You might also have heard that you should use the fgets() function, with stdin as the FILE * parameter, instead of gets(). Most people stop after saying that, but that doesn't actually give you the same result. gets() removes the '\n' character from the input but fgets() does not. That means you must manually remove the '\n' before passing the string to fopen(), or for many other uses.


Here is getsafe() function. Like gets() and fgets() both, it returns a pointer to char. This is either the pointer which was passed to it, or NULL if end of file or an error occurred. Like gets(), it removes the '\n' at the end of the string, if there is one. The prototype is:
char *getsafe(char *buffer, int count);
Here is the function:
char *getsafe(char *buffer, int count)
{
char *result = buffer, *np;
if ((buffer == NULL or count <>result = NULL;

else if (count == 1)

*result = '\0';

else if ((result = fgets(buffer, count, stdin)) != NULL)

if (np = strchr(buffer, '\n'))

*np = '\0';

return result;

}


That's all it takes to safely get input strings from the standard input with the '\n' removed.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home