Expressions that have an integral type can be added to or subtracted from a pointer, resulting in a value of the pointer type. If the resulting pointer is not a valid member of the container, or one past the last element of the container, the behavior of the additive operator is undefined. The C++ Standard, [expr.add], paragraph 5 [ISO/IEC 14882-2014], states, in part in part, states the following:
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
Because iterators are a generalization of pointers, the same constraints apply to additive operators with random access iterators. Specifically, the C++ Standard, [iterator.requirements.general], paragraph 5, states the following:
Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding sequence. These values are called past-the-end values. Values of an iterator
ifor which the expression*iis defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.
...
In this noncompliant code example, a random access iterator from a std::vector is used in an additive expression, but the resulting value could be outside the bounds of the container rather than a past-the-end value:.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <iostream>
#include <vector>
void f(const std::vector<int> &c) {
for (auto i = c.begin(), e = i + 20; i != e; ++i) {
std::cout << *i << std::endl;
}
} |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <algorithm>
#include <vector>
void f(const std::vector<int> &c) {
const auto estd::vector<int>::size_type maxSize = i + std::min(20, c.size());
for (auto i = c.begin(), ie != e;i ++i) {
// ...
}
} |
Noncompliant Code Example (Linear Address Space)
In this noncompliant code example, an attempt is made to determine if a pointer addition will cause a linear address space wraparound:
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <cstddef>
void f(const char *buf, std::size_t len) {
// Check for overflow
if (buf + len < buf) {
len = -(std::size_t)buf - 1;
}
} |
This code resembles the test for wraparound from the sprint() function as implemented for the Plan 9 operating system. If buf + len < buf evaluates to true, len is assigned the remaining space minus one byte. However, because the expression buf + len < buf constitutes undefined behavior, compilers can assume this condition will never occur and optimize away the entire conditional statement.
Implementation Details
In GCC versions 4.2 and later, code that performs checks for wrapping that depend on undefined behavior (such as the code in this noncompliant code example) are optimized away; no object code to perform the check appears in the resulting executable program [VU#162289]. This is of special concern because it often results in the silent elimination of code that was inserted to provide a safety or security check. For GCC 4.2.4 and later, this optimization may be disabled with the -fno-strict-overflow option.
Compliant Solution (Linear Address Space)
In this compliant solution, both references to buf are cast to std::uintptr_t. Because std::uinptr_t is an unsigned integral type of sufficient size to store a pointer value, C++ guarantees that it has modulo behavior.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <cstdint> void f(const char *buf, std::size_t len) { // Check for overflow auto bint = reinterpret_cast<std::uintptr_t>(buf); if (bint + len < bintstd::min(maxSize, c.size()); i != e; ++i) { len = -(std::size_t)bint - 1;// ... } } |
...
Risk Assessment
If adding or subtracting an integer to a pointer results in a reference to an element outside the array or one past the last element of the array object, the behavior is undefined but frequently leads to a buffer overflow or buffer underrun, which can often be exploited to run arbitrary code. Iterators and standard template library containers exhibit the same behavior and caveats as pointers and arrays.
Rule | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level | |
|---|---|---|---|
CTR55-CPP | High | Likely | No |
No |
P9 |
L2 |
Automated Detection
Tool | Version | Checker | Description |
|---|
| Helix QAC |
| DF3526, DF3527, DF3528, DF3529, DF3530, DF3531, DF3532, DF3533, DF3534 | |||||||
| Klocwork |
| ITER.ADVANCE.NONADJACENT | |||||||
| LDRA tool suite |
| 567 S | Enhanced Enforcement | ||||||
| Parasoft C/C++test |
| CERT_CPP-CTR55-a | Do not add or subtract a constant with a value greater than one from an iterator | ||||||
| Polyspace Bug Finder |
| CERT C++: CTR55-CPP | Checks for possible iterator overflows (rule partially covered). |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
| SEI CERT C Coding Standard | ARR30-C. Do not form or use out-of-bounds pointers or array subscripts |
| MITRE CWE | CWE 129, Unchecked Array Indexing |
Bibliography
| [Banahan |
| 2003] | Section 5.3, "Pointers" Section 5.7, "Expressions Involving Pointers" |
| [ISO/IEC 14882-2014] | Subclause 5.7, "Additive Operators" |
...
...