tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: Bug in scanf?



On Mon, Dec 08, 2025 at 08:45:00PM +0100, Anders Magnusson wrote:
> I just stumbled over something which may be a bug in scanf()...?
> This example is in C99 7.19.6.2 clause 20.
> 
> This lines;
> 
>     int count; float quant; char units[21], item[21];
>     count = sscanf("100ergs of energy\n",  "%f%20s of %20s", &quant, units,
> item);
> 
> Should have a count of 0;
>     count = 0; // "100e" fails to match "%f"

The standard C angle interested me, so I put this to PhD
(who happens to be the WG14 editor) off-list.

I relay his analysis from <https://pony.social/@thephd/115743060918796972>:
> This is not a bug.
> 
> 100e is not a decimal number. 100 is, 100e1 is, 100e is not.
> The grammar for fscanf with %f follows strtod, and strtod follows
> §6.4.5.3 Floating literals. The grammar is unambiguous that 100e
> does not match because e requires at least 1 digit.
> 
> We can argue about how much lookahead is required to make this a
> parsing error (read e and assume an exponent, then fail) vs. failing
> more "gracefully" (read e but do not assume an exponent until
> digit-sequence and possibly a preceiding sign are parsed, and if
> not just make it text) but the stdio text would support doing either
> because fscanf has a "only puts one character back at most" floor
> limit for algorithm implementation (e.g., a more or less forward-only
> algorithm is the minimum requirement). So seeing e and then no
> digits and then failing is valid, and SO is seeing e and then
> realizing there's no more digits and rewinding the e and the the
> extra digit is also a valid implementation.
> 
> "That's stupid" it's a library from C89. Of course it's fucking
> stupid.

Attachment: signature.asc
Description: PGP signature



Home | Main Index | Thread Index | Old Index