Uninitialized variable


An uninitialized variable is a variable that is declared but is not set to a definite known value before it is used.

Use of uninitialized variables is similar to use of uninitialized memory and might be a source of errors of different kinds to occur during program execution.

Consider the following example:

int Sum(int n)
{
  int sum, i;
 
  for (i = 0; i < n; i++)
  {
    sum = sum + 1;
  }
 
  return sum;
}

The 'sum' variable wasn't assigned an initial value, and now it contains some "garbage". In some cases, if you're lucky enough, it may also be set to zero enabling the function to work correctly. But in general the function return result is unpredictable. What is tricky about these errors is that the program may work correctly for a long time. One day, after you have changed to another compiler or made some refactoring or other changes, the program will start producing wrong results. Moreover, it may behave quite differently every time you run it.

To avoid such errors in the C++ language, it's the best practice to set all variables to initial values as you declare them. And it's best to declare variables immediately before using them, when their initial values are already known. Taking this into account, we can fix our code sample in the following way:

int Sum(int n)
{
  int sum = 0;
 
  for (int i = 0; i < n; i++)
  {
    sum = sum + 1;
  }
 
  return sum;
}

The PVS-Studio analyzer can perform some diagnostics that allow you to detect certain errors related to the use of uninitialized variables. For example: V573, V614.

References


Bugs Found

Checked Projects
336
Collected Errors
12 743