Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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
bgColor#ccccff
langcpp
#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

...