>
>
>
V6079. Value of variable is checked aft…


V6079. Value of variable is checked after use. Potential logical error is present. Check lines: N1, N2.

The analyzer has detected the following issue. First, the value of a variable or expression is used as an index to an array or collection. And only then is this value compared with 0 or the size of the array or collection. This may indicate a logic error in the code or a typo in one of the comparisons.

Consider the following example:

int idx = getPosition(buf);
buf[idx] = 42;
if (idx < 0) return -1;

If the value of 'idx' happens to be less than zero, evaluating the 'buf[idx] ' expression will cause an error. The analyzer will point out two lines when reporting this code. The first line is where the 'idx' variable is compared with 0. The second line is where 'idx' was used prior to the check.

Fixed version:

int idx = getPosition(buf);
if (idx < 0) return -1;
buf[idx] = 42;

Similarly, the analyzer will issue a warning if the variable is compared with the array's size:

int[] buf = getArrayValue(/*params*/);
buf[idx] = 42;
if (idx < buf.length) return;

Fixed version:

int[] buf = getArrayValue(/*params*/);
if (idx < buf.length) return;
buf[idx] = 42;

The analyzer will also report an issue if the variable is used as an array index and checked in the same expression:

void f(int[] arr)
{
  for (int i = 0; arr[i] < 10 && i < arr.length; i++)
  {
    System.out.println("arr[i] = " + arr[i]);
  }
}

In this case, if all the elements of the array are less than 10, the condition will be checking a value outside the array's bounds at the last iteration. And that means ArrayIndexOutOfBoundsException!

Fixed version:

void f(int[] arr)
{
  for (int i = 0; i < arr.length && arr[i] < 10; i++)
  {
    System.out.println("arr[i] = " + arr[i]);
  }
}

This diagnostic is classified as:

You can look at examples of errors detected by the V6079 diagnostic.