When I try to compile C code that uses the gets() function, I get a warning: the gets function is dangerous and should not be used. Why is it usually a bad idea to use gets()?
May be your compiler is gcc isn’t it? The function gets() is no more in use because it needs exactly the same number of characters that it is going to read. Modern compilers have abolished and I prefer you to use fgets() instead of gets() don’t struck on old try new.
gets() is an insecure method of taking in input data. It is vulnerable to what is known as a buffer overflow. For instance, if you have something like
char string; gets(string);
And the user enters “I am fabulous” then the number of characters exceeds the length of your string. Hence, you would get a compiler error. fgets() allows you to specify the number of bytes to read but it comes with it’s own problems (the unread bytes are just left there in the input buffer. You’ll have to flush the input buffer which is too much of a headache).
Just use scanf(). It’s quite easy to use and does the job of parsing stuff as required for you. It also has it’s problems but generally works quite well.
This should help: http://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
The first internet worm (the Morris Internet Worm) escaped 27 years ago (1988-11-02), and it used gets() and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn’t know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.
You should forget you ever heard that gets() existed.
The C11 standard ISO/IEC 9899:2011 eliminated gets() as a standard function, which is A Good Thing™. Sadly, it will remain in libraries for many years (meaning ‘decades’) for reasons of backwards compatibility.
if the input is “I am fabulous”
it prints only “I” because scanf breaks at white spaces.
So scanf is not an alternative to gets.
can u tell how to flush the buffer after reading ?