Re: Why is it dangerous?



On 10 Aug 2008 at 0:59, Richard Heathfield wrote:
Julian said:
a_03.c:(.text+0x4d): warning: the `gets' function is dangerous
and should not be used.

The functionality of gets() is defined by ISO; it takes a pointer to
the first character in a buffer, and stores an entire line from stdin
into that buffer, *regardless of the buffer's size*!! There is no safe
way to use such a function.

Of course, this is nonsense. There is a perfectly safe way to use
gets(), namely by being in control of what appears on stdin. Here in the
real world, people write all sorts of scraps of in-house code to run
once and forget about. They use fscanf() without elaborate error
checking, because they are 100% sure of the format of the input files.
gets() is no different.

Of course, in any production code, or any code at all where someone
other than the programmers will be able to decide what appears on stdin,
then gets() should not be used, the return value of p=malloc(10) should
be checked, etc. etc.

Instead of gets(), use whatever safe function is available on your
platform. For example, on GNU systems there is a getline() function
provided by stdio.h, which will dynamically allocated a big enough
buffer using malloc(). Or, roll your own getline function if portability
is a big issue for you.

.



Relevant Pages

  • Re: getc() vs. fgetc()
    ... Since stdin does not contain ... this is both safe and efficient. ... > standard streams or not. ... I presume it was for historical reasons; that is, ...
    (comp.lang.c)
  • Re: *scanf in Harbison and Steele
    ... The difference between fgets and gets is at least that fgets takes ... the output buffer. ... Though I've been told that stdin come with the food in C, must you declare: ...
    (comp.lang.c)
  • Re: [OT] Re: How, exactly, does kbhit( ) work?
    ... >was one buffer at issue, but I think now there are two. ... >One is made by C in memory, and is connected with stdin, ... and it is this buffer that kbhit looks at. ... >Either way, in my test code, by the time kbhit executed ...
    (comp.lang.c)
  • Re: *scanf in Harbison and Steele
    ... The difference between fgets and gets is at least that fgets takes ... Another difference is that fgetstakes a count argument, and will not write more than the specified number of bytes to the buffer, which is the key feature that makes fgetssafer than gets. ... Though I've been told that stdin come with the food in C, ... So the only useful thing to do with the return value is to compare it with either NULL or buffer. ...
    (comp.lang.c)
  • Re: why the usage of gets() is dangerous.
    ... that always terminates the program with an error message if the buffer is ... With this device we have a perfectly safe getsfucntion. ... It can only fill the buffer correctly or report that it has been exceeded. ...
    (comp.lang.c)