sscanf always generates error condition

Steve Summit scs at adam.mit.edu
Tue May 7 12:02:59 AEST 1991


In article <1991May1.024357.7750 at dg-rtp.dg.com> hunt at dg-rtp.rtp.dg.com writes:
>In article <1991Apr30.233554.1321 at agate.berkeley.edu>, ilan343 at violet.berkeley.edu (Geraldo Veiga) writes:
>> 	System error: Bad file number
>> 	(This message corresponds to errno=9)
>
>In the test case, errno is being used without having a value assigned to
>it, so the "9" is just garbage that happened to be in the memory
>associated with errno at the time.

Actually, "Bad file number" is an extremely likely inadvertent
errno value after a successful call to sscanf, and not because of
any random memory contents.

sscanf (and, equivalently, sprintf) work by setting up a
temporary buffered file descriptor (FILE *) which uses as its I/O
buffer the user's string.  When the string is exhausted, the
stdio code typically falls into the same buffer refilling code
(often an internal routine called _filbuf) which attempts to read
more data from the associated file into the buffer.  The low-
level file descriptor for a string pseudo-file is usually set to -1,
so the read fails, with EBADF.  (This error ends up looking like
EOF, which is what we'd want to happen at the end of the sscanf
string anyway.  Actually, ferror() would probably report that an
error had occurred, except that by the time sscanf has returned,
the temporary FILE *, and its error indication, has disappeared.)

BSD systems (and probably many others) set the internal _IOSTRG
flag on string pseudo-files, which can be used to avoid an
inadvertent read or write to a bad file descriptor in these
cases.

As has been (correctly) pointed out, however, it's not incorrect
for ISC's sscanf to be leaving EBADF in errno, because (to quote
from an old version of the comp.lang.c frequently-asked questions
list), "it is only meaningful for a program to inspect the
contents of errno after an error has occurred (that is, after a
library function that sets errno on error has returned an error
code)."  (The more common guise under which this issue comes up
is "Why does errno contain ENOTTY after a call to printf?")

                                            Steve Summit
                                            scs at adam.mit.edu



More information about the Comp.unix.programmer mailing list