Copying data into a container that is not large enough to hold that data results in a buffer overflow. To prevent such errors, data copied to the destination container must be restricted based on the size basis of the destination container's size, or, preferably, the destination container must be guaranteed to be large enough to hold the data to be copied.
...
Copies can be made with the std::memcpy() function. However, the std::memmove() and std::memset() functions can also have the same vulnerabilities because they overwrite a block of memory without checking that the block is valid. Such issues are not limited to C standard library functions; standard template library (STL) generic algorithms like such as std::copy(), std::fill(), and std::transform() also assume valid output buffer sizes.
Note that since because iterators are a generalization of pointers, this rule applies to iterators and pointers equally [ISO/IEC 14882-2014].
...
STL containers can be subject to the same vulnerabilities as array datatypesdata types. The std::copy algorithm provides no inherent bounds checking , and can lead to a buffer overflow. In this noncompliant code example, a vector of integers is copied from src to dest using std::copy(). Since Because std::copy() does nothing to expand the dest vector, the program will overflow the buffer on copying the first element.
...
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.
...
| 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());
// ...
}
|
...
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. This , which guarantees the destination container will become sufficiently large enough to hold the elements provided.
...
Copying data to a buffer that is too small to hold that data results in a buffer overflow. Attackers can exploit this condition to execute arbitrary code.
...
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...