Why Gets Function So Dangerous That It Should Not Be Used

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?

Best Answer

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

[sourcecode]char* fgets(char *string, int length, FILE * stream);[/sourcecode]

(fgets, if it reads an entire line, will leave the '\n' in the string; you’ll have to deal with that.)

gets remained an official part of the language up to the 1999 ISO C standard, but it was officially removed in the 201Best Answertandard. Most C implementations still support it, but at least gcc issues a warning for any code that uses it.

[custom-related-posts title=”You may Also Like:” none_text=”None found” order_by=”title” order=”ASC”]

Leave a Comment