CodeQL 文档

‘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

点击查看 CodeQL 仓库中的查询

此查询查找对 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;
  }
}

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私