Rule Definition
Using a variable that is not initialized can lead to unexpected behavior. Some compilers may detect the use of uninitialized variables in some cases, but none can detect them all. For example the following sample remains undetected:
void take_ptr(int * ptr)
{
printf("%lx", *ptr);
}
void main()
{
int c;
take_ptr(&c);
}
Remediation
See samples and remediation samples.
Violation Code Sample
// SAMPLE 1: Basic example
int main()
{
int c; // VIOLATION
}
// SAMPLE 2: Non violations
void main()
{
int c;
c = 0; // is NOT considered as a violation
double d = f(); // not a violation
}
// SAMPLE 3: Initialization in branch
// Initialization done in conditional branching or in a called method are considered as a violation.
void main()
{
int i;
if (...)
i = 3; // VIOLATION
}
// SAMPLE 4: Use in function call
void f( int * p) { *p = 3; }
void g()
{
int i;
f( &i); // VIOLATION
}
Fixed Code Sample
// SAMPLE 1: Basic example
int main()
{
int c = 0;
}
// SAMPLE 3: Initialization in branch
// Initialization done in conditional branching or in a called method are considered as a violation.
void main()
{
int i = 0; // REMEDIATION
if (...)
i = 3;
}
// SAMPLE 4: Use in function call
// Although this usage is safe, we cannot know it in 'g' until we read the body of 'f'. If the implementation of 'f' changes, calling 'g' may become invalid. It is safer to initialize 'i' in 'g':
void f( int * p) { *p = 3; }
void g()
{
int i = 0; // REMEDIATION
f( &i);
}
Reference
"Black Hat Federal 2006 : Attack on uninitialized Variables":http://www.blackhat.com/presentations/bh-europe-06/bh-eu-06-Flake.pdf
Related Technologies
C++
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.