Joh*_*nck 4 c scanf integer-overflow language-lawyer
今天我了解到,scanf()C 中不检查整数是否可以用指定类型表示。例如:
#include <stdio.h>
int main(void)
{
short num;
int ret = scanf("%hd", &num);
printf("read %d, returned %d\n", num, ret);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的系统(Clang/MacOS)上,上面的程序会说“returned 1”,意思是scanf()读取指定的标记,即使输入不可表示,例如4223215425243525443245234453. man scanf说:
当输入字符与格式字符不匹配时,扫描停止。当无法进行输入转换时,扫描也会停止。
C 标准是否要求这种行为,或者是否允许 的实现者scanf()将超出范围的数字输入视为无效(因此在上述情况下返回 0)?如果需要这种行为,我希望引用标准中的说法。