[comp.lang.c] gets limits?

tim@scsmo1.UUCP (04/24/89)

What does ANSI say about gets.  It seem to me that there is NO way to
figure out how big to make the buffer for the beast.  I have assumed
that gets can be approximated by:
#define gets(x)   fgets(s,BUFSIZ,stdin)

Since assumptions tend to cause problems, (like the internet worm :-)
what rules should be followed with gets.  Personaly I like the idea of
taking the binary editor and nuking some character in the "gets" string
so it won't be found by the linker.

I often see gets reading in a string that is put in an 80 byte array.
What is the maximum number of characters? is it BUFSIZ?  How about
GETSBUFSIZ?  

If ANSI does not say anything about this, I think they missed the boat as
this could be the single most unsecure feature of C.

tim hogard
tim@scsmo1.uucp

barmar@think.COM (Barry Margolin) (04/26/89)

The only time it is correct to use gets() is when you know for sure
the maximum line length.  This could be the case if you're reading a
file that was written by another program, whose output is in a
regular, known format.  If you've still got a card reader, it could be
useful for reading card images.

Gets() should NOT be used when reading user input or files that are
likely to have been edited by the user.  Of course, since gets() also
defaults the stream to standard input, it's likely that most potential
uses of gets() would read from the terminal.  In other words, it's
hardly ever a good idea to use gets().

The most obvious (to me, at least) implementation of gets() doesn't
have any limit on the number of characters it will read.  It would
look something like (please excuse any C syntax errors, I'm mainly a
Lisp hacker):

char *gets(s)
char *s;
{
    int c;

    while (((c = getchar()) != EOF) && (c != '\n'))
	*s++ = c;
    /* Add trailing null */
    *s = '\0';

    return s;
}

Since it uses the provided string as its input buffer, it has no
inherent limit on the size.  But since it isn't given a limit as a
parameter, it will go beyond the end of the buffer if the line is too
long.  And no matter how large you make the buffer, someone can make
an input stream with a longer line (some terminal drivers have limits
on the size of a single line, but the input could be redirected to a
huge file containing no newlines).

Barry Margolin
Thinking Machines Corp.

barmar@think.com
{uunet,harvard}!think!barmar

gwyn@smoke.BRL.MIL (Doug Gwyn) (04/26/89)

In article <9300001@scsmo1.UUCP> tim@scsmo1.UUCP writes:
>What does ANSI say about gets.  It seem to me that there is NO way to
>figure out how big to make the buffer for the beast.

Yes, that's right.

>what rules should be followed with gets[?]

Use it only when you know that the buffer will not be overrun.
In other case, use something like fgets().