What's so bad about scanf anyway???

Zev Sero zvs at bby.oz.au
Mon Nov 12 12:48:50 AEST 1990


Roy   = roy%cybrspc at cs.umn.edu (Roy M. Silvernail)
Avery = avery at netcom.UUCP (Avery Colter)

Avery> In the self-teaching course I have here, scanf is the most often used
Avery> input function. I don't see gets used much at all.

Roy> The problem with scanf() is that it can behave unpredictably when you
Roy> give it badly formatted input. It's better, IMHO, to gets() a whole
Roy> line, check its validity and _then_ sscanf() it into the target

When you are not absolutely, 100% sure that the input from stdin will
be what the program expects (e.g. when stdin is coming from a user, or
even from a file if you didn't generate it yourself), scanf() is a bad
idea, for the reason Roy mentioned.  When stdin is a terminal (as it
is in almost all cases), you must expect the user to type absolutely
anything that pops into its putative brain, or simply to lean on the
keyboard and give you a nice random string!

But for exactly the same reason, you should never, never, never use
gets().  The gets() function does not check how many characters it
reads.  It just keeps going until it sees a newline.  If the array
you're storing the thing in overflows, tough bikkies.  H&S warn
against the use of gets() for this reason, but I was flabbergasted to
see a textbook published by Microsoft which consistently used gets()
for input.  The safe way to read input from a user is to use fgets()
and sscanf().

  char buf[1000];
  int i;
  if (!fgets (buf, sizeof buf, stdin)) {
    [complain]
  }
  i = sscanf (buf, [whatever]);
  if (i != [the right number]) {
    [complain]
  }


Only use scanf() and/or gets() when you are sure that the program is
only ever called as a pipe from another program which you know will
not produce any surprises, or with stdin coming from a file generated
by such a program.
---
				Zev Sero  -  zvs at bby.oz.au
If a compiler emits correct code purely by divine guidance and
has no memory at all, it can still be a C compiler.
				-   Chris Torek



More information about the Comp.lang.c mailing list