Search code examples
clinuxgccstdiofgets

Why is fgets() considered in gcc(linux) and what is the alternative to use it?


Possible Duplicate:
Why is the `gets' function is dangerous? Why should not be used?

I am propting user to input a string using fgets() which will be analysed using scanf() for distinguishing integers, floats and chars.I want a reliable program but i'm getting the following warning using gcc:

In function main': : warning: thegets' function is dangerous and should not be used.

Can anybody tell me why it is dangerous and what is the safe alternative to it? If someone can tell me the gravity of fatalness of fgets() , it would be really helpful.


Solution

  • You may be a little confused. In a nutshell: gets is bad, fgets is fine.

    The man page explains why gets should not be used:

    BUGS
           Never use gets().  Because it is impossible to tell without knowing the
           data  in  advance  how  many  characters  gets() will read, and because
           gets() will continue to store characters past the end of the buffer, it
           is  extremely  dangerous  to  use.   It has been used to break computer
           security.  Use fgets() instead.
    

    fgets takes the size of the buffer as one of its arguments and, if used correcly, does not have this problem.

    The FAQ has an entry with more details.