Originally posted by skylark:
In Linux you'll get a warning, "the gets function is dangerous..." just ignore it
No, do
not, I repeat do
not ignore that warning. The gets() function is
extremely dangerous and introduces a point of failure in your program. Do not use it. Ever. Use fgets() instead.
oSpIkEo, the char type in C only holds a single character, not a string. To store a string, you must use an array of char:
Code:
char x; /* can store single characters only */
char a[6]; /* can store strings up to 5 characters long */
In C, all strings are terminated with a 0 value, so the size of the char array must be at least 1 more than the size of the string you are trying to store. In other words, if you store the string "Hello" to a char array, the actual contents of the array are {'H', 'e', 'l', 'l', 'o', 0}.
The reason gets() is dangerous is that it will attempt to store as many characters as you try to enter, regardless of the size of the target buffer. If you have a target buffer of 10 characters and someone enters a string that's 100 characters long, 90 of those characters will be stored past the end of your buffer and clobber whatever's there, causing a crash or other weird behavior (the Morris worm exploited this misfeature). fgets() allows you to specify how many characters to read, allowing you to prevent such problems.
Example (untested!):
Code:
#include <stdio.h>
#include <string.h>
int main (void)
{
char name[34]; /* can hold names up to 32 characters long */
/* plus newline character and nul terminator */
char *n; /* used to find newline character in buffer */
printf ("What's your name: ");
fgets (name, sizeof name, stdin);
if (!(n = strchr (name, '\n')))
{
/*
** We didn't find a newline in the target buffer,
** meaning the user typed in a name longer than
** we can handle.
*/
printf ("That name's too long for me!\n");
}
else
{
/*
** Strip out the newline
*/
*n = 0;
printf ("Hi, %s\n", name);
}
return 0;
}
Normally you'll check the return value of fgets() to make sure the read actually succeeded.
[This message was edited by jbode on May 05, 2002 at 14:03.]