CodeQL 文档

不一致的空值检查

ID: cpp/inconsistent-null-check
Kind: problem
Security severity: 
Severity: error
Precision: medium
Tags:
   - reliability
   - correctness
   - statistical
   - non-attributable
   - external/cwe/cwe-476
Query suites:
   - cpp-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

常见的缺陷来源是忘记检查函数调用的结果是否为 NULL。此规则检测到对函数的调用,其中大多数其他调用检查结果是否为 NULL,但此特定调用未检查。这与代码的其余部分不一致,可能是一个缺陷,或者至少会让其他开发人员感到困惑。

标记的调用不一定会导致运行时错误,但所有调用都需要审核。不要在每个标记的位置机械地添加空值检查,因为不必要的空值检查会让其他开发人员感到非常困惑。熟悉代码的开发人员很可能立即知道在出现空结果时应该采取什么措施,如果并非如此,很可能该函数的 API 存在一些混乱之处。

建议

诊断在特定调用时的上下文中,被调用函数是否真的可以返回 NULL。如果是这种情况,则应更新代码以处理这种情况。如果调用在该位置不能返回 NULL,则可以添加断言以记录代码不处理 NULL。此记录非常重要,因为大多数调用都期望收到 NULL 值。

示例

struct property {
  char *name;
  int value;
};

struct property * get_property(char *key);
struct property * get_property_default(char *key, int default_value);

void check_properties() {
  // this call will get flagged since most
  // calls to get_property handle NULL
  struct property *p1 = get_property("time");
  if(p1->value > 600) {
    ...
  }

  // this call will not get flagged since
  // the result of the call is checked for NULL
  struct property *p2 = get_property("time");
  if(p2 != NULL && p2->value > 600) {
    ...
  }

  // this call will not get flagged since calls
  // to get_property_default rarely handle NULL
  struct property *p3 = get_property_default("time", 50);
  if(p3->value > 60) {
    ...
  }
}

参考资料

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