Potentially uninitialized local variable¶
ID: cpp/uninitialized-localKind: path-problemSecurity severity: 7.8Severity: warningPrecision: mediumTags: - security - external/cwe/cwe-665 - external/cwe/cwe-457Query suites: - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
A local non-static variable of a non-class type has an undefined value before it is initialized. For example, it is incorrect to rely on an uninitialized integer to have the value0.
Recommendation¶
Review the code and consider whether the variable should have an initializer or whether some path through the program lacks an assignment to the variable.
Example¶
The functionabsWrong does not initialize the variablej in the case wherei=0. FunctionsabsCorrect1 andabsCorrect2 remedy this deficiency by adding an initializer and adding an assignment to one of the paths through the program, respectively.
intabsWrong(inti){intj;if(i>0){j=i;}elseif(i<0){j=-i;}returnj;// wrong: j may not be initialized before use}intabsCorrect1(inti){intj=0;if(i>0){j=i;}elseif(i<0){j=-i;}returnj;// correct: j always initialized before use}intabsCorrect2(inti){intj;if(i>0){j=i;}elseif(i<0){j=-i;}else{j=0;}returnj;// correct: j always initialized before use}
References¶
ISO/IEC 9899:2011:Programming languages - C (Section 6.3.2.1).
Common Weakness Enumeration:CWE-665.
Common Weakness Enumeration:CWE-457.