When I try to compile C code that uses the gets()
function with GCC, I get this warning:
(.text+0x34): warning: the `gets' function is dangerous and should not be used.
I remember this has something to do with stack protection and security, but I'm not sure exactly why.
How can I remove this warning and why is there such a warning about using gets()
?
If gets()
is so dangerous then why can't we remove it?
In order to use gets
safely, you have to know exactly how many characters you will be reading, so that you can make your buffer large enough. You will only know that if you know exactly what data you will be reading.
Instead of using gets
, you want to use fgets
, which has the signature
char* fgets(char *string, int length, FILE * stream);
(fgets
, if it reads an entire line, will leave the '\n'
in the string; you'll have to deal with that.)
It remained an official part of the language up to the 1999 ISO C standard, but it was officially removed by the 2011 standard. Most C implementations still support it, but at least gcc issues a warning for any code that uses it.