I learned today that scanf()
in C does not check if integers are representable in the specified type. For example:
#include <stdio.h>
int main(void)
{
short num;
int ret = scanf("%hd", &num);
printf("read %d, returned %d\n", num, ret);
return 0;
}
On my system (Clang/MacOS), the above program will say "returned 1" meaning scanf()
read the specified token even if the input is not representable, such as 4223215425243525443245234453
. man scanf
says:
Scanning stops when an input character does not match such a format character. Scanning also stops when an input conversion cannot be made.
Does the C standard require this behavior, or would it also be permissible for an implementor of scanf()
to consider out-of-range numeric inputs invalid (and so return 0 in cases like the above)? If this behavior is required, I'd appreciate a quote from the standard saying so.
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.
So absolutely anything is permissible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With