NO

Author Topic: scanf bug  (Read 2158 times)

Dickie-Doo

  • Guest
scanf bug
« on: March 26, 2015, 07:26:23 PM »
The short program attached shows a problem with scanf when the destination variable is an unsigned 32-bit integer %u or %lu.
If the value is over limit, scanf is supposed to return ULONG_MAX (0xFFFFFFFF), but what it actually seems to return
is X & 0xFFFFFFFF.  Try entering 4294967297 and you should get X=1!
Interestingly, the 64-bit version %llu seems to work correctly, returning ULLONG_MAX.
I'm using RC8.00, 64-bit version under Win7 and making a 64-bit console program.

moreson

  • Guest
Re: scanf bug
« Reply #1 on: March 26, 2015, 09:45:39 PM »
My reading of the standard says it's undefined what happens.

"Except in the case of a % specifier, the input item (or, in the case of a %n directive, the count of input characters) is converted to a type appropriate to the conversion specifier.
...
If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined."


It does say the *format* shall be the same as strtoul(p, 0, 10), but it does not say the *behavior* shall be the same (strtoul will indeed return ULONG_MAX on overflow).
"%u: Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 10 for the base argument. The corresponding argument shall be a pointer to unsigned integer."

Bug report for glibc marked it as invalid:
https://www.sourceware.org/bugzilla/show_bug.cgi?id=6453