CodeQL 文档

潜在的未初始化局部变量

ID: cpp/uninitialized-local
Kind: path-problem
Security severity: 7.8
Severity: warning
Precision: medium
Tags:
   - security
   - external/cwe/cwe-665
   - external/cwe/cwe-457
Query suites:
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

在局部非静态变量被初始化之前,非类类型的局部变量的值是不确定的。例如,依赖未初始化的整数值为 0 是不正确的。

建议

检查代码,考虑变量是否应该具有初始化器,或者程序中的某些路径是否缺少对变量的赋值。

示例

函数 absWrongi = 0 的情况下没有初始化变量 j。函数 absCorrect1absCorrect2 分别通过添加初始化器和在程序的其中一条路径中添加赋值操作来弥补这一缺陷。

int absWrong(int i) {
	int j;
	if (i > 0) {
		j = i;
	} else if (i < 0) {
		j = -i;
	}
	return j; // wrong: j may not be initialized before use
}

int absCorrect1(int i) {
	int j = 0;
	if (i > 0) {
		j = i;
	} else if (i < 0) {
		j = -i;
	}
	return j; // correct: j always initialized before use
}

int absCorrect2(int i) {
	int j;
	if (i > 0) {
		j = i;
	} else if (i < 0) {
		j = -i;
	} else {
		j = 0;
	}
	return j; // correct: j always initialized before use
}

参考

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