parts/6.30.Off-by-oneError-XZH.md

6.30 Off-by-one Error [XZH]

6.30.1 Applicability to language

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

6.30.2 Avoidance mechanisms for language users

To avoid the vulnerability or mitigate its ill effects, C++ software developers can:

See also the C++ Core guidelines ES.1, ES.42, ES.71, SL.con.3 (more to come)