Why is this an issue?
Variables should be initialized before their use to avoid unexpected behaviors due to garbage values.
Noncompliant code example
int function(int flag, int b) {
int a;
if (flag) {
a = b;
}
return a; // Noncompliant - "a" has not been initialized in all paths
}
Compliant solution
int function(int flag, int b) {
int a = 0;
if (flag) {
a = b;
}
return a;
}
Resources
- MITRE, CWE-457 - Use of Uninitialized Variable
- MISRA C:2004, 9.1 - All automatic variables shall have been assigned a value before being used.
- MISRA C++:2008, 8-5-1 - All variables shall have a defined value before they are used.