[comp.lang.c] ungetc and scanf

karl@haddock.ISC.COM (Karl Heuer) (01/09/88)

In article <6978@brl-smoke.ARPA> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
>In article <38060@sun.uucp> guy@gorodish.Sun.COM (Guy Harris) writes:
>>The trouble is that "_doscan" uses "ungetc" ...
>
>Ah, now I see the problem.  It is the caller's buffer, not stdio's,
>that is being modified.  That is clearly a bug, which is relatively
>easy to fix in sscanf() by strdup()ing the caller's buffer.

Is strdup() part of the ANSI library now?  It wasn't in the Oct86 Draft.

If sscanf() calls strdup() (or if it calls malloc() directly), it has to deal
with the possibility of running out of memory.  I'd just as soon avoid the
extra complication.

If I'm not mistaken, the character which sscanf() pushes back via ungetc() is
always the same as the last character read via getc().  Hence the buffer need
not be modified.  It would suffice to replace the ungetc() call with the
equivalent of "--fp->_ptr".

Btw, the Oct86 Draft says that "one character of pushback is guaranteed".
It's unclear to me whether this requires an ungetc() to succeed immediately
after a scanf().  (Sure, we all know that scanf() calls ungetc() if it reads
too far, but the Draft doesn't concern itself with internal details.)  Has
this been clarified in a more recent issue?

Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint

gwyn@brl-smoke.ARPA (Doug Gwyn ) (01/09/88)

In article <2193@haddock.ISC.COM> karl@haddock.ima.isc.com (Karl Heuer) writes:
>Is strdup() part of the ANSI library now?  It wasn't in the Oct86 Draft.

No, but it's in the SVID.  It's such a small function that the ANSI C
implementation can easily have its own version, with a reserved name or
simply as a static function in the scanf.c source file.

>If I'm not mistaken, the character which sscanf() pushes back via ungetc() is
>always the same as the last character read via getc().  Hence the buffer need
>not be modified.  It would suffice to replace the ungetc() call with the
>equivalent of "--fp->_ptr".

That's a better approach, but you have to also deal with unbuffered I/O.

>Btw, the Oct86 Draft says that "one character of pushback is guaranteed".
>It's unclear to me whether this requires an ungetc() to succeed immediately
>after a scanf().

Yes, it does.  It is not stated that scanf() uses ungetc() and in fact
many people think that it shouldn't.