Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C scanf() prohibited from checking that integers are in range?

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.

like image 344
John Zwinck Avatar asked Oct 18 '25 23:10

John Zwinck


1 Answers

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.

like image 91
n. 1.8e9-where's-my-share m. Avatar answered Oct 20 '25 20:10

n. 1.8e9-where's-my-share m.