RN.INDEX

Suspicious use of index before negative check

It's important to make sure that a buffer index variable defined as int isn't a negative number, as this could lead to a buffer overflow. However, if the variable is employed as an index in code before it's checked, the check is either redundant or it should precede the use of the index. The RN.INDEX checker flags instances in which a variable used as a buffer index is brought into use before it's checked for a negative value.

Vulnerability and risk

If the buffer index in the negative value check is known to be positive, the check is redundant. Otherwise, the check should precede the use of the index or it's pointless.

Vulnerable code example

Copy
   public int foo(int *a, int t)
   {
     int x;
     x = a[t];

     if (t >= 0)
       x++;

     return x;
   }

In this example, Klocwork reports RN.INDEX at line 5, in which the index variable 't' is checked for a negative value. Since it's already been used as a buffer index in line 4, the check is too late. If variable 't' is known to be positive, the check is redundant. If not, the check should precede the use of the variable as an index.

Fixed code example

Copy
   public int foo(int *a, int t)
   {
     int x;
     if (t >= 0)
     {
       x = a[t];
       x++;
     }

     return x;
   } 

In the fixed code example, the variable is checked for a negative value in line 4, before it's used as an index in line 6.

Security training

Application security training materials provided by Secure Code Warrior.