Local, automatic variables can assume unexpected values if they are used read before they are initialized. The C++ Standard, [dcl.init], paragraph 12, states [ISO/IEC 14882-2003] Section 8.5, paragraph 9 says: "... if 2014]:
If no initializer is specified for
...
an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object
...
In most cases, compilers warn about uninitialized variables. These warnings should be resolved as recommended by MSC00-CPP. Compile cleanly at high warning levels.
has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced. If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:
— If an indeterminate value of unsigned narrow character type is produced by the evaluation of:
— the second or third operand of a conditional expression,
— the right operand of a comma expression,
— the operand of a cast or conversion to an unsigned narrow character type, or
— a discarded-value expression,
then the result of the operation is an indeterminate value.
— If an indeterminate value of unsigned narrow character type is produced by the evaluation of the right operand of a simple assignment operator whose first operand is an lvalue of unsigned narrow character type, an indeterminate value replaces the value of the object referred to by the left operand.
— If an indeterminate value of unsigned narrow character type is produced by the evaluation of the initialization expression when initializing an object of unsigned narrow character type, that object is initialized to an indeterminate value.
The default initialization of an object is described by paragraph 7 of the same subclause:
To default-initialize an object of type
T
means:
— ifT
is a (possibly cv-qualified) class type, the default constructor forT
is called (and the initialization is ill-formed ifT
has no default constructor or overload resolution results in an ambiguity or in a function that is deleted or inaccessible from the context of the initialization);
— ifT
is an array type, each element is default-initialized;
— otherwise, no initialization is performed.
If a program calls for the default initialization of an object of a const-qualified typeT
,T
shall be a class type with a user-provided default constructor.
As a result, objects of type T
with automatic or dynamic storage duration must be explicitly initialized prior to having their value read as part of an expression, except if T
is a class type or array thereof, or an unsigned narrow character type. If T
is an unsigned narrow character type, it may be used to initialize an object of unsigned narrow character type, which results in both objects having an indeterminate value. This can be used to implement copy operations like std::memcpy()
without triggering undefined behavior.
Additionally, memory dynamically allocated with a new
expression is default-initialized when the new-initialized is omitted. Memory allocated by the standard library function std::calloc()
is zero-initialized. Memory allocated by the standard library function std::realloc()
assumes the values of the original pointer, but may not initialize the full range of memory. Memory allocated by any other means (std::malloc()
, allocator objects, operator new()
, etc) is assumed to be default-initialized.
Objects of static or thread storage duration are zero-initialized before any other initialization takes place [ISO/IEC 14882-2014], and need not be explicitly initialized prior to having their value readAdditionally, memory allocated by functions such as malloc()
should not be used before being initialized as its contents are indeterminate.
Noncompliant Code Example
In this noncompliant code example, the set_flag()
function is intended to set the variable sign
to 1
if number
is positive and -1
if number
is negative. However, the programmer neglected to account for number
being 0
. If number
is 0
, then sign
remains uninitialized. Because sign
is uninitialized, and again assuming that the architecture makes use of a program stack, it uses whatever value is at that location in the program stack. This may lead to unexpected or otherwise incorrect program behavior.an uninitialized local variable is evaluated as part of an expression to print its value, resulting in undefined behavior:
Code Block | ||||
---|---|---|---|---|
| ||||
void set_flag(int number, int *sign_flag) { if (sign_flag == nullptr) { return; } if (number > 0) { *sign_flag = 1; } else if (number < 0) { *sign_flag = -1; } } void func(int number#include <iostream> void f() { int signi; set_flag(number, &sign); /* use sign */ } |
Compilers assume that when the address of an uninitialized variable is passed to a function, the variable is initialized within that function. Because compilers frequently fail to diagnose any resulting failure to initialize the variable, the programmer must apply additional scrutiny to ensure the correctness of the code.
Implementation Details
Microsoft Visual Studio 2005, Visual Studio 2008, GCC version 3.4.4, and GCC version 4.1.3 fail to diagnose this error.
Compliant Solution
std::cout << i;
} |
Compliant Solution
In this compliant solution, the object is initialized prior to printing its value:This defect results from a failure to consider all possible data states (see MSC01-CPP. Strive for logical completeness). Once the problem is identified, it can be trivially repaired by accounting for the possibility that number
can be equal to 0.
Code Block | ||||
---|---|---|---|---|
| ||||
void set_flag(int number, int *sign_flag) { if (sign_flag == nullptr) { return; } if (number >= 0) { /* account for number being 0 */ *sign_flag = 1; } else { assert(number < 0); *sign_flag = -1; } } void func(int number) { int sign; set_flag(number, &sign); /* use sign */ } #include <iostream> void f() { int i = 0; std::cout << i; } |
Noncompliant Code Example
In this noncompliant code example, an int *
object is allocated by a new-expression, the programmer mistakenly fails to set the local variable error_log
to the msg
argument in the report_error()
function [mercy 06]. Because error_log
has not been initialized, on architectures making use of a program stack, it assumes the value already on the stack at this location, which is a pointer to the stack memory allocated to the password
array. The sprintf()
call copies data in password
until a null byte is reached. If the length of the string stored in the password
array is greater than the size of the buffer
array, then a buffer overflow occursbut the memory is points to is not initialized. The object's pointer value, and the value it points to are printed to the standard output stream. Printing the pointer value is well-defined, but attempting to print the value pointed to yields an indeterminate value, resulting in undefined behavior.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> #include <ctype.h> #include <string.h> int do_auth(void<iostream> void f() { charint *username; i = charnew *passwordint; /* Get username and password from user, return -1 if invalid */ } void report_error(const char *msgstd::cout << i << ", " << *i; } |
Compliant Solution
In this compliant solution, the memory is properly initialized prior to printing its value:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <iostream> void f() { const charint *error_log; i = char buffer[24]new int; sprintf(buffer, "Error: %s", error_log)*i = 12; printf("%s\n", buffer); } int main(void) { if (do_auth() == -1) { report_error("Unable to login"); } return 0; } std::cout << i << ", " << *i; } |
Noncompliant Code Example
In this noncompliant code example, the class member variable C
is not initialized by the default constructor. Despite the local variable o
being default-initialized, the report_error()
function has been modified so that error_log
is properly initializedthe use of C
within the call to S::f()
results in the use of an indeterminate value.
Code Block | ||||
---|---|---|---|---|
| ||||
void report_error(const char *msg) {
const char *error_log = msg;
char buffer[24];
sprintf(buffer, "Error: %s", error_log);
printf("%s\n", buffer);
}
|
This solution is still problematic in that a buffer overflow will occur if the null-terminated byte string referenced by msg
is greater than 17 bytes, including the NULL terminator. The solution also makes use of a "magic number," which should be avoided (see DCL06-CPP. Use meaningful symbolic constants to represent literal values in program logic).
Compliant Solution
class S {
int C;
public:
int f(int I) const { return I + C; }
};
void f() {
S o;
int i = o.f(10);
} |
Compliant Solution
In this compliant solution, S
is given a default constructor that initializes the class member variable C
:In this solution, the magic number is abstracted and the buffer overflow is eliminated.
Code Block | ||||
---|---|---|---|---|
| ||||
enum {max_buffer = 24}; void report_error(const char *msg)class S { const char *error_log = msg; char buffer[max_buffer]; int C; public: snprintf(buffer, sizeof( buffer), "Error: %s", error_log); cout << buffer << endl; } |
This solution is compliant provided that the null-terminated byte string referenced by msg
is 17 bytes or less, including the null terminator.
Compliant Solution
A much simpler, less error prone, and better performing compliant solution is shown below.
Code Block | ||||
---|---|---|---|---|
| ||||
void report_error(const char *msgS() : C(0) {} int f(int I) const { return I + C; } }; void f() { coutS << "Error: " << msg << endlo; int i = o.f(10); } |
Risk Assessment
Accessing Reading uninitialized variables generally leads to unexpected is undefined behavior and can result in unexpected program behavior. In In some cases these types of flaws may , these security flaws may allow the execution of arbitrary code.
VU#925211 in the OpenSSL package for Debian Linux, and other distributions derived from Debian, is said to reference uninitialized memory. One might say that uninitialized memory caused the vulnerability, but not directly. The original OpenSSL code used uninitialized memory as an additional source of randomness to an already-randomly-generated key. This generated good keys, but caused the code-auditing tools Valgrind and Purify to issue warnings. Debian tried to fix the warnings with two changes. One actually eliminated the uninitialized memory access, but the other weakened the randomness of the keysReading uninitialized variables for creating entropy is problematic, because these memory accesses can be removed by compiler optimization. VU#925211 is an example of a vulnerability caused by this coding error.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP33-CPP | highHigh | probableProbable | mediumMedium | P12 | L1 |
Automated Detection
The LDRA tool suite Version 7.6.0 can detect violations of this rule.
Fortify SCA Version 5.0 can detect violations of this rule, but will return false positives if the initialization was done in another function.
Splint Version 3.1.1 can detect violations of this rule.
GCC Compiler Version 4.4.0 can detect some violations of this rule when the -Wuninitialized
flag is used.
Compass/ROSE automatically detects simple violations of this rule, although it may return some false positives. It may not catch more complex violations, such as initialization within functions taking arguments to uninitialized variables. It does catch the second noncompliant code example, and can be extended to catch the first as well.
The Coverity Prevent Version 5.0 UNINIT checker can find cases of an uninitialized variable being used before it is initialized, although it cannot detect cases of uninitialized members of a struct
. Because Coverity Prevent cannot discover all violations of this rule further verification is necessary.
Klocwork can detect violations of this rule with the UNINIT.* checkers. See Klocwork Cross Reference
Tool | Version | Checker | Description | |||||
---|---|---|---|---|---|---|---|---|
PRQA QA-C++ | ||||||||
Include Page | PRQA QA-C++_v | 2961,2962,2963,2966, 2967,2968,2971,2972, 2973,2976, 2977, 2978 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the the CERT website.
Other Languages
...
Related Guidelines
...
...
Bibliography
[ |
...
...
2014] |
...
8.5, "Initializers" Clause 5, "Expressions" 5.3.4, "New" 12.6.2, "Initializing Bases and Members" | |
[Lockheed Martin 05] |
...
Rule 142, "All variables shall be initialized before use |
...
" |
...