CXX.SUSPICIOUS_INDEX_CHECK.ZERO
The CXX.SUSPICIOUS_INDEX_CHECK.ZERO checker finds defects when a suspicious index check against zero is present before accessing an array, but the index value is not checked against the upper array boundary.
Vulnerability and risk
If an array is accessed by an index that is beyond the array’s size, it can lead to data corruption, misbehavior, or crashing.
Mitigation and prevention
To prevent buffer overflow, check that the index is within the lower and upper boundary range limit before accessing an array at a specific index.
Vulnerable code example
int get_index();
void foo()
{
int err = 0;
const int SIZE = 10;
int arr[SIZE];
int index = get_index();
if (index > 0) {
arr[index]=10;
}
}
Since there is a suspicious index check against zero present before accessing an array, but the index value is not checked against the upper array boundary, Klocwork reports CXX.SUSPICIOUS_INDEX_CHECK.ZERO at line 9 to warn users about the suspicious index check on line 8.
Fixed code example
int get_index();
void foo()
{
int err = 0;
const int SIZE = 10;
int arr[SIZE];
int index = get_index();
if (index >= 0 && index < 10) {
arr[index] = 10;
}
}
Buffer overflow is not possible because the constraint "index >= 0 && index < 10" on line 8 rules out all bad behavior.
Related checkers
External guidance
Security training
Application security training materials provided by Secure Code Warrior.