What's so bad about scanf anyway??? (really what's bad about gets)

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Tue Nov 20 15:13:00 AEST 1990


In article <879 at jonlab.UUCP> jon at jonlab.UUCP (Jon H. LaBadie) wrote
> I've a vague recollection that declaring input arrays to be BUFSIZ
> in length provides some protection to overflow by gets(3C).
In article <1990Nov16.165203.18786 at zoo.toronto.edu>,
 henry at zoo.toronto.edu (Henry Spencer) replied
: Nope.  Except insofar as making the arrays longer reduces the probability
: of somebody overflowing them.  There is no magic associated with BUFSIZ.

The original question asked specifically about input from terminals.
Some operating systems (UNIX, VMS, OS/2, others) place a limit on the
number of characters in a line entered at a keyboard.  In OS/2 it's 255.
The POSIX standard defines a parameter, I think it's MAXCANON or something
like that.  The limit has typically been 255, but there's no reason it
couldn't be more.  Since each read() from the keyboard is going to be
stored in a stdio buffer, BUFSIZ had better be at least as large as this
limit, so declaring your arrays that big should be enough to handle
terminal input.  Except...

gets() will keep on reading from stdin until it hits a \n or an EOF.
Lines entered from a keyboard _normally_ end with a \n, but they don't
have to.  Let <EOF> represent your end-of-file character on a UNIX system
and let <junk70> represent 70 printing characters.  Then
	<junk70><EOF>
	<junk70><EOF>
	<junk70><EOF>
	<junk70><EOF>
	<junk70><EOF>
	<junk70><EOF>
	<junk70><EOF>
	<junk70><EOF>
	<junk70><EOF>
	<junk70><RET>
will result in gets() seeing a line with 701 characters, refilling the
stdio buffer several times.  (I've tried this.  It works.)  Since VMS
returns a record to the caller when you hit <RET> _or_ a function key,
I imagine that it might be possible to play a similar trick in VMS.

So the answer is, for your own private use, yes you can get away with
using BUFSIZ as a limit for keyboard input, but don't do dare do that
in a program you sell to customers.

-- 
I am not now and never have been a member of Mensa.		-- Ariadne.



More information about the Comp.lang.c mailing list