scanf gives different results on short and long overflow

M

myx

Hi. I've noticed interesting thing in scanf(). When overflow happens,
it behaves differently depending on what type specifier do you use.
Here is an example:
-------
long a;
scanf("%lx", &a);
printf("%lx", a);
-------
input:
ffffffff0 /* overflow */
output:
ffffffff /* result contain ULONG_MAX */

In second case, I'm trying to overflow short int:
-------
short a;
scanf("%hx", &a);
printf("%hx", a);
-------
input:
ffff0 /* overflow */
output:
fff0 /* result contain ffff0 % (USHRT_MAX+1) */

I think I know why it behaves so. But I think that it is not very good
behaviour, because scanf must return or ULONG_MAX, or num % (ULONG_MAX
+1) (in this particular case).
Am I wrong?
 
B

Ben Bacarisse

myx said:
Hi. I've noticed interesting thing in scanf(). When overflow happens,
it behaves differently depending on what type specifier do you use.
Here is an example:
-------
long a;
scanf("%lx", &a);
printf("%lx", a);
-------
input:
ffffffff0 /* overflow */
output:
ffffffff /* result contain ULONG_MAX */

In second case, I'm trying to overflow short int:

These examples have a problem -- %x needs an unsigned not a signed
integer (or pointer to one for scanf) of the right size.
-------
input:
ffff0 /* overflow */
output:
fff0 /* result contain ffff0 % (USHRT_MAX+1) */

I think I know why it behaves so. But I think that it is not very good
behaviour, because scanf must return or ULONG_MAX, or num % (ULONG_MAX
+1) (in this particular case).
Am I wrong?

Sadly, the scanf functions can do pretty much what they like in cases
like this. The behaviour is undefined if the value can't be
represented in the type used to receive it even for unsigned types.
The standard talks about the "result of the conversion" but this is
the conversion of the input characters, not of any conversion to the
target type and the result is "placed" rather than "placed (as if by
assignment)" in the target. Undefined behaviour occurs whenever the
result can't be represented in the target type.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top