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:
#include
int main(void)
{
char name [25];
printf("Enter your name: ");
fflush(stdout);
if (gets(name) != NULL)
printf("Hello and Goodbye %s\n", name);
return 0;
}
What do you think will happen if the user types fifty characters into your twenty-five character array? What if the user types one hundred characters? Two hundred??
The answer is that gets() will fill up your array and then keep on going, trying to write to memory past the end of the array which your program does not have the right to access. A program crash is likely. Some notorious computer viruses have based their attack on deliberately overflowing buffers used by calling gets().
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 my 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:
#include
#include
char *getsafe(char *buffer, int count) {
char *result = buffer, *np;
if ((buffer == NULL) (count < 1))
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;
}
1 ความคิดเห็น:
I c how useful it is, but i don't know much about C. So i could come back to see it again later. gg
แสดงความคิดเห็น