Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

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

     
1   public int foo(int *a, int t)
2   {
3     int x;
4     x = a[t];

5     if (t >= 0)
6       x++;

7     return x;
8   } 

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

     
1   public int foo(int *a, int t)
2   {
3     int x;
4     if (t >= 0)
5     {
6       x = a[t];
7       x++;
8     }

9     return x;
10   } 

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.