RABV.CHECK
Accessing array value beyond the array’s size
The checker looks for cases of accessing the array before the index is checked for being within array boundaries.
Vulnerability and risk
If the array is accessed by an index that is beyond the array’s size, it might corrupt data, lead to misbehavior, and/or crash.
Vulnerable code example 1
// some function returning an index
int get_index();
void main() {
const int SIZE = 10;
int arr[SIZE];
int index = get_index();
arr[index] = 0;
if (index >= SIZE) {
return;
}
}
Klocwork reports a defect for line 10 indicating that the index is used for accessing the array before the index is checked for validity at line 12.
Fixed code example 1
// some function returning an index
int get_index();
void main() {
const int SIZE = 10;
int arr[SIZE];
int index = get_index();
if (index >= SIZE) {
return;
}
arr[index] = 0;
}
The problem from the previous snippet is fixed; the index is checked before it is used for accessing the array.
Vulnerable code example 2
int get_index();
void set(int* arr, int index) {
arr[index] = 0;
}
void main() {
int SIZE = 10;
int arr[SIZE];
int index = get_index();
set(arr, index);
if (index >= SIZE) {
return;
}
}
Similar to example 1, but the array is not accessed in the same function “main”, instead being passed to another function “set” as a parameter. Klocwork reports a defect for line 12 indicating that the index is used for accessing the array inside the function “set” before it is checked for validity at line 14.
Fixed code example 2
int get_index();
void set(int* arr, int index) {
arr[index] = 0;
}
void main() {
int SIZE = 10;
int arr[SIZE];
int index = get_index();
if (index >= SIZE) {
return;
}
set(arr, index);
}
The defect is fixed in the same manner; the index is now checked for validity at line 12 before it is passed to the function “set” at line 16.
Related checkers
External guidance
Security training
Application security training materials provided by Secure Code Warrior.