‘scanf’ 类函数的返回值检查错误¶
ID: cpp/incorrectly-checked-scanf
Kind: problem
Security severity: 7.5
Severity: warning
Precision: high
Tags:
- security
- correctness
- external/cwe/cwe-253
Query suites:
- cpp-code-scanning.qls
- cpp-security-extended.qls
- cpp-security-and-quality.qls
此查询查找对 scanf
类函数的调用,这些调用没有进行正确的返回值检查。具体来说,它会标记 scanf
的使用情况,其中返回值仅与零进行比较。
‘scanf’ 系列函数在 IO 失败的情况下返回 EOF
(一个负值),或者返回从输入中成功读取的项数。因此,仅仅检查返回值是否不为零是不够的。
建议¶
确保对 scanf
的所有使用都检查返回值是否与预期的参数数量匹配,而不仅仅与零进行比较。
示例¶
以下示例展示了保护 scanf
输出的不同方法。在 BAD 示例中,结果仅与零进行比较。在 GOOD 示例中,结果与预期的匹配数量进行比较。
{
int i, j;
// BAD: The result is only checked against zero
if (scanf("%d %d", &i, &j)) {
use(i);
use(j);
}
// BAD: The result is only checked against zero
if (scanf("%d %d", &i, &j) == 0) {
i = 0;
j = 0;
}
use(i);
use(j);
if (scanf("%d %d", &i, &j) == 2) {
// GOOD: the result is checked against 2
}
// GOOD: the result is compared directly
int r = scanf("%d %d", &i, &j);
if (r < 2) {
return;
}
if (r == 1) {
j = 0;
}
}
参考资料¶
SEI CERT C++ 编码标准:ERR62-CPP. 检测将字符串转换为数字时的错误.
SEI CERT C 编码标准:ERR33-C. 检测和处理标准库错误.
cppreference.com: scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s.
通用弱点枚举:CWE-253.