The vulnerability as described in ISO/IEC TR 24772-1:2019 clause 6.30 exists in C++.
Arrays are a common place for off by one errors to manifest. In C++, arrays are indexed starting at 0, causing the common mistake of looping from 0 to the size of the array as in:
int foo() {
int a[10];
int i;
for (i=0, i<=10, i++)
...return (0);
}
C++ mitigates the issue of sentinel values in strings document in ISO/IEC 24772-1 clause 6.30 by providing the string
class and the string_view
class.
C++ does not flag accesses outside of array bounds, so an off by one error may not be as detectable in C++ as in some other languages. Several good and freely available tools can be used to help detect accesses beyond the bounds of arrays that are caused by an off by one error. However, such tools will not help in the case where only a portion of the array is used, and the access is still within the bounds of the array.
C++ mitigates these issues by providing
Range-based for loops
std
algorithms
Iterator style loops terminated by !=
Container classes
gsl::span
(soon to be std::span
)
To avoid the vulnerability or mitigate its ill effects, C++ software developers can:
Use the avoidance mechanisms of ISO/IEC 24772-1 clause 6.30.5.
Use careful programming, testing of border conditions, and static analysis tools to detect off-by-one errors in C++.
Use range-based for loops, std algorithms, iterator style loops terminated by !=, or container classes in preference to C-style arrays and structures.
See also the C++ Core guidelines ES.1, ES.42, ES.71, SL.con.3 (more to come)