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[5];
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: C library function - scanf()
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.
char ar[100];
scanf("%s",ar);
cout<<ar<<endl;
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 ?