Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki MarkupLocal, automatic variables can assume _ unexpected _ values if they are used read before they are initialized. \[The C++ Standard, [dcl.init], paragraph 12 [ISO/IEC 14882-2003|AA. Bibliography#ISO/IEC 14882-2003]\] Section 8.5, paragraph 9 says: "... if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value". In practice, this value defaults to whichever values are currently stored in stack memory. While uninitialized memory often contains zero, this is not guaranteed. Consequently, uninitialized memory can cause a program to behave in an unpredictable or unplanned manner and may provide an avenue for attack.

In most cases, compilers warn about uninitialized variables. These warnings should be resolved as recommended by MSC00-CPP. Compile cleanly at high warning levels.

Additionally, 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.

Code Block
bgColor#FFCCCC

void set_flag(int number, int *sign_flag) {
  if (sign_flag == NULL) {
    return;
  }
  if (number > 0) {
    *sign_flag = 1;
  }
  else if (number < 0) {
    *sign_flag = -1;
  }
}

void func(int number) {
  int sign;

  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

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
bgColor#ccccff

void set_flag(int number, int *sign_flag) {
  if (sign_flag == NULL) {
    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 */
}

Noncompliant Code Example

Wiki Markup
In this noncompliant code example, the programmer mistakenly fails to set the local variable {{error_log}} to the {{msg}} argument in the {{report_error()}} function \[[mercy 06|AA. Bibliography#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 occurs.

Code Block
bgColor#FFCCCC

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int do_auth(void) {
  char *username;
  char *password;

  /* Get username and password from user, return -1 if invalid */
}

void report_error(const char *msg) {
  const char *error_log;
  char buffer[24];

  sprintf(buffer, "Error: %s", error_log);
  printf("%s\n", buffer);
}

int main(void) {
  if (do_auth() == -1) {
    report_error("Unable to login");
  }
  return 0;
}

Noncompliant Code Example

In this noncompliant code example, the report_error() function has been modified so that error_log is properly initialized.

Code Block
bgColor#ffcccc

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

In this solution, the magic number is abstracted and the buffer overflow is eliminated.

Code Block
bgColor#ccccff

enum {max_buffer = 24};

void report_error(const char *msg) {
  const char *error_log = msg;
  char buffer[max_buffer];

  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
bgColor#ccccff

void report_error(const char *msg) {
  cout << "Error: " << msg << endl;
}

Risk Assessment

Accessing uninitialized variables generally leads to unexpected program behavior. In some cases these types of 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 keys.

2014], states the following: 

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 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:
— if T is a (possibly cv-qualified) class type, the default constructor for T is called (and the initialization is ill-formed if T 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);
— if T 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 type T, 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 before having their value read as part of an expression unless T is a class type or an array thereof or is 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 technique can be used to implement copy operations such as 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(), and so on) 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 before having their value read.

Reading uninitialized variables for creating entropy is problematic because these memory accesses can be removed by compiler optimization.  VU925211 is an example of a vulnerability caused by this coding error [VU#925211].

Noncompliant Code Example

In this noncompliant code example, an uninitialized local variable is evaluated as part of an expression to print its value, resulting in undefined behavior.

Code Block
bgColor#FFcccc
langcpp
#include <iostream>
 
void f() {
  int i;
  std::cout << i;
}

Compliant Solution

In this compliant solution, the object is initialized prior to printing its value.

Code Block
bgColor#ccccff
langcpp
#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, but the memory it 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
bgColor#FFcccc
langcpp
#include <iostream>
 
void f() {
  int *i = new int;
  std::cout << i << ", " << *i;
}

Compliant Solution

In this compliant solution, the memory is direct-initialized to the value 12 prior to printing its value.

Code Block
bgColor#ccccff
langcpp
#include <iostream>
 
void f() {
  int *i = new int(12);
  std::cout << i << ", " << *i;
}

Initialization of an object produced by a new-expression is performed by placing (possibly empty) parenthesis or curly braces after the type being allocated. This causes direct initialization of the pointed-to object to occur, which will zero-initialize the object if the initialization omits a value, as illustrated by the following code.

Code Block
int *i = new int(); // zero-initializes *i
int *j = new int{}; // zero-initializes *j
int *k = new int(12); // initializes *k to 12
int *l = new int{12}; // initializes *l to 12

Noncompliant Code Example

In this noncompliant code example, the class member variable c is not explicitly initialized by a ctor-initializer in the default constructor. Despite the local variable s being default-initialized, the use of c within the call to S::f() results in the evaluation of an object with indeterminate value, resulting in undefined behavior.

Code Block
bgColor#FFcccc
langcpp
class S {
  int c;
 
public:
  int f(int i) const { return i + c; }
};
 
void f() {
  S s;
  int i = s.f(10);
}

Compliant Solution

In this compliant solution, S is given a default constructor that initializes the class member variable c.

Code Block
bgColor#ccccff
langcpp
class S {
  int c;
 
public:
  S() : c(0) {}
  int f(int i) const { return i + c; }
};
 
void f() {
  S s;
  int i = s.f(10);
}

Risk Assessment

Reading uninitialized variables is undefined behavior and can result in unexpected program behavior. In some cases, these security flaws may allow the execution of arbitrary code.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP33

EXP53-CPP

high

High

probable

Probable

medium

Medium

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.

...

Tool

Version

Checker

Description

Astrée

Include Page
Astrée_V
Astrée_V

uninitialized-read
Partially checked
Clang
Include Page
Clang_V
Clang_V
-Wuninitialized
clang-analyzer-core.UndefinedBinaryOperatorResult
Does not catch all instances of this rule, such as uninitialized values read from heap-allocated memory.
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

LANG.STRUCT.RPL
LANG.MEM.UVAR

Return pointer to local
Uninitialized variable
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

DF726, DF2727, DF2728, DF2961, DF2962, DF2963, DF2966, DF2967, DF2968, DF2971, DF2972, DF2973, DF2976, DF2977, DF978


Klocwork
Include Page
Klocwork_V
Klocwork_V
UNINIT.CTOR.MIGHT
UNINIT.CTOR.MUST
UNINIT.HEAP.MIGHT
UNINIT.HEAP.MUST
UNINIT.STACK.ARRAY.MIGHT
UNINIT.STACK.ARRAY.MUST
UNINIT.STACK.ARRAY.PARTIAL.MUST
UNINIT.STACK.MIGHT
UNINIT.STACK.MUST

LDRA tool suite
Include Page
LDRA_V
LDRA_V

53 D, 69 D, 631 S, 652 S

Partially implemented

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V
CERT_CPP-EXP53-a
Avoid use before initialization
Parasoft Insure++

Runtime detection
Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C++: EXP53-CPP

Checks for:

  • Non-initialized variable
  • Non-initialized pointer

Rule partially covered.

PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V546, V573, V614V670, V679, V730, V788, V1007V1050

RuleChecker
Include Page
RuleChecker_V
RuleChecker_V
uninitialized-read
Partially checked

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the the CERT website.

Other Languages

...

Related Guidelines

...

...

References

...

Bibliography

...

14882-2014]Clause 5, "Expressions"
Subclause 5.3.4, "New"
Subclause 8.5, "Initializers"
Subclause 12.6.2, "Initializing Bases and Members" 
[Lockheed Martin 2005]Rule 142, All variables shall be initialized before use


...

Image Added Image Added Image Added 2003|AA. Bibliography#ISO/IEC 14882-2003]\] Section 8.5 Initializers. \[[Lockheed Martin 05|AA. Bibliography#Lockheed Martin 05]\] AV Rule 142 All variables shall be initialized before use. \[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "LAV Initialization of Variables" \[[mercy 06|AA. Bibliography#mercy 06]\]EXP32-CPP. Do not access a volatile object through a non-volatile reference      03. Expressions (EXP)      EXP34-CPP. Ensure a null pointer is not dereferenced