Versions Compared

Key

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

Local, automatic variables can assume unexpected values if they are used before they are initialized. The C standard specifies, "If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate" [ISO/IEC 9899:2011]. (See also undefined behavior 1011 of Annex J.)

In the common case, on implementations that make use of a program stack, this value defaults to whichever values are currently stored in stack memory. While uninitialized memory often contains zeroes, this is not guaranteed. On implementations that include trap representations, reading an uninitialized object of any type other than unsigned char (including int) may trigger a trap. (See undefined behavior 1112 of Annex J.) Consequently, uninitialized memory can cause a program to behave in an unpredictable or unplanned manner, lead to undefined behavior, and can provide an avenue for attack.

...

Note also that unless doing so is prohibitive for performance reasons, an additional defense-in-depth practice worth considering is to initialize local variables immediately after declaration. While Although compilers and static analysis tools often detect uses of uninitialized variables when they have access to the source code, diagnosing the problem is difficult or impossible when either the initialization or the use takes place in object code the source code of which is inaccessible to the tool.

...

In the noncompliant code example below, the function mbrlen() is passed the address of an automatic mbstate_t object that has not been properly initialized, leading to undefined behavior. See undefined behavior 188 in Section J.2 of C99behavior 200 in Annex J of C11.

Code Block
bgColor#ffcccc
langc
void f(const char *mbs) {
  size_t len;
  mbstate_t state;

  len = mbrlen(mbs, strlen(mbs), &state);

  /* ... */
}

...

Before being passed to a multibyte conversion function, an mbstate_t object must be either initialized to the initial conversion state or set to a value that corresponds to the most recent shift state by a prior call to a multibyte conversion function. The compliant solution below sets the mbstate_t object to the initial conversion state by setting it to all zeros.

...

ISO/IEC 9899:2011 Section 6.7.9, "Initialization"

ISO/IEC TR 17961 (Draft) Referencing uninitialized memory [uninitref]

ISO/IEC TR 24772 "LAV Initialization of Variables"

...