retiring gets(3)

David Chase chase at Ozona.orc.olivetti.com
Tue Nov 15 08:05:50 AEST 1988


In article <20588 at apple.Apple.COM> desnoyer at Apple.COM (Peter Desnoyers) writes:
>Perhaps I'm being naive, but wouldn't changing
>  char buf[x];  gets( buf);
>to
>  char * buf;   buf = malloc( x);  gets( buf);
>eliminate most (not all) of the security hole associated with gets()?

In practice it would make invasion difficult.  Do bear in mind that it
might not make it impossible; memory allocation may look like a black
box to you, but with a little care purposeful overwriting is possible
(for example, in testing a new garbage collector we discovered a bug
tickled by the collector that (independent of input) consistently
appeared at the same line while examining a structure at the same
address.  The cause?  Overrunning of a data structure in the heap.)
(Yes, a garbage collector for C --
           ~ftp/sun-source/gc.shar at titan.rice.edu
It works on Sun3s, Sun4s, Vaxes.  Send mail with subject "help" to
"archive-server at rice.edu" if you lack FTP access.)

What I fail to understand is why you couldn't just as easily write

  char * buf;   buf = malloc(x);  fgets(buf, x, stdin);

(yes, I know that fgets leaves the newline in the string)

People say again and again "but I know how big the input is in my
programs, so it's safe to use 'gets'".  If you know how big the input
is, then you might as well say it.  People talk about performing
certain hand-optimizations in a habitual way; is it too much to ask
people to acquire habits that make their programs more robust?
Optimizing a correct program is easier than correcting an optimized
program (more fun, too).

David



More information about the Comp.lang.c mailing list