UNINIT.STACK.MUST

Uninitialized variable

The UNINIT.STACK.MUST checker finds instances in which a local variable of a non-class type is read when it hasn't been initialized.

Vulnerability and risk

In C++, stack variables aren't initialized by default. They generally contain random junk data from the current content of stack memory. The uninitialized data may contain values that cause program flow to change in unintended ways, possibly with security implications.

Mitigation and prevention

To avoid initialization problems, make sure all variables and resources are initialized explicitly before their first usage. Take note of complex conditional situations and make sure that all paths include the initialization.

Vulnerable code example

Copy
  struct s {
    int a;
    int b;
  };
  
  int main() {
    struct s x;
    x.b = 0;
    return x.a;
 }

Klocwork flags line 9, indicating that the value of the uninitialized variable 'x.a' is used when it hasn't been initialized.