retiring gets(3)

Richard A. O'Keefe ok at quintus.uucp
Sat Nov 19 16:07:33 AEST 1988


In article <19278 at ism780c.isc.com> marv at ism780.UUCP (Marvin Rubenstein) writes:
>I would like to suggest a library routine to replace gets say,
>safegets(buffer,count), which for lines no longer then count would behave
>like gets, and for lines longer than count would place the first count-1
>characters of the line into the buffer followed by a '\0'.  The value
>returned by safegets is the line length (or EOF).

Believing that co-operation is more constructive than criticism, I posted
just such a routine to comp.sources.misc a couple of days ago, called
getsafe().  The return value is the number of characters in the line
_including_ the \n, or 0 for EOF.

However, a couple of other people on the net have pointed out problems with
my code, such as the possibility of someone supplying >2**32 characters of
input so that the counter would wrap around, and some things to be done for
dpANS compatibility.  I have included these changes, and in a day or two
(in case anyone else spots something wrong) will post the revised version.

Trying to make getsafe() absolutely foolproof (and portable) has been an
educational experience for me.  I have come to the conclusion that there
is something _worse_, far far worse, than gets(), and that is the routines
which people took great care to make safe, but because of C's under-
specified integer arithmetic, aren't.  (Leaving aside the fact that in
UNIX it is _impossible_ for a C program to be sure of getting the right
value of errno -- and no, 'volatile' doesn't fix that, it just stops the
compiler making it worse.)



More information about the Comp.lang.c mailing list