Array offset used before range check¶
ID: cpp/offset-use-before-range-check
Kind: problem
Security severity: 8.2
Severity: warning
Precision: medium
Tags:
- reliability
- security
- external/cwe/cwe-120
- external/cwe/cwe-125
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
The program contains an and-expression where the array access is defined before the range check. Consequently the array is accessed without any bounds checking. The range check does not protect the program from segmentation faults caused by attempts to read beyond the end of a buffer.
Recommendation¶
Update the and-expression so that the range check precedes the array offset. This will ensure that the bounds are checked before the array is accessed.
Example¶
The find
function can read past the end of the buffer pointed to by str
if start
is longer than or equal to the length of the buffer (or longer than len
, depending on the contents of the buffer).
int find(int start, char *str, char goal)
{
int len = strlen(str);
//Potential buffer overflow
for (int i = start; str[i] != 0 && i < len; i++) {
if (str[i] == goal)
return i;
}
return -1;
}
int findRangeCheck(int start, char *str, char goal)
{
int len = strlen(str);
//Range check protects against buffer overflow
for (int i = start; i < len && str[i] != 0 ; i++) {
if (str[i] == goal)
return i;
}
return -1;
}
Update the and-expression so that the range check precedes the array offset (for example, the findRangeCheck
function).
References¶
cplusplus.com: C++: array.
Wikipedia: Bounds checking.
Common Weakness Enumeration: CWE-120.
Common Weakness Enumeration: CWE-125.