...
This hazard applies to any algorithm that takes a destination iterator, expecting to fill it with values. Most of the STL algorithms expect the destination container to have sufficient space to hold the values provided.
Compliant Solution (
...
Sufficient initial capacity)
The proper way to use std::copy()
is to ensure the destination container can hold all the elements being copied to it. This compliant solution enlarges the capacity of the vector prior to the copy operation:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <algorithm> #include <vector> void f(const std::vector<int> &src) { // Initialize dest with src.size() default-inserted elements std::vector<int> dest(src.size()); std::copy(src.begin(), src.end(), dest.begin()); // ... } |
Compliant Solution (
...
Per-element growth)
An alternative approach is to supply a std::back_insert_iterator
as the destination argument. This iterator expands the destination container by one element for each element supplied by the algorithm, which guarantees the destination container will become sufficiently large to hold the elements provided.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ Coding Standard | STR50-CPP. Guarantee that storage for strings has sufficient space for character data and the null terminator |
SEI CERT C Coding Standard | ARR38-C. Guarantee that library functions do not form invalid pointers |
MITRE CWE | CWE 119, Failure to Constrain Operations within the Bounds of an Allocated Memory Buffer CWE 805, Buffer Access with Incorrect Length Value |
...