gets limits?

Barry Margolin barmar at think.COM
Wed Apr 26 05:50:36 AEST 1989


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 at think.com
{uunet,harvard}!think!barmar



More information about the Comp.lang.c mailing list