scanf%d在大输入时的段错误

Voo*_*Voo 6 c scanf

所以我在一些c代码上运行了一些静态代码分析器,让我惊讶的一件事就是警告:

int val;
scanf("%d", &val);
Run Code Online (Sandbox Code Playgroud)

其中说,对于足够大的输入,这可能会导致段错误.实际上这确实可以实现.现在修复很简单(指定一些宽度;毕竟我们知道有效整数最多可能有多少个位置,具体取决于架构)但我想知道的是为什么这首先发生这种情况以及为什么这不是被认为是libc中的一个错误(还有一个简单的解决方法)?

现在我假设首先出现这种行为的原因是我失踪了?

编辑:好的,因为问题似乎没有那么明确,更多的解释:没有代码分析器一般不会警告scanf,而是关于scanf读取没有特定宽度指定的数字.

所以这是一个最小的工作示例:

#include <stdlib.h>
#include <stdio.h>

int main() {
    int val;
    scanf("%d", &val);
    printf("Number not large enough.\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我们可以通过发送一个巨大的数字(使用例如Python)获得段错误:

import subprocess
cmd = "./test"
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, shell=True)
p.communicate("9"*50000000000000)
# program will segfault, if not make number larger
Run Code Online (Sandbox Code Playgroud)

小智 3

如果静态分析器是 cppcheck,那么它会因为 glibc 中的错误而发出警告,该错误已被修复:http://sources.redhat.com/bugzilla/show_bug.cgi ?id=13138