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.

...

Bibliography

[ISO/IEC 14882-2014]

Subclause 25.3, "Mutating Sequence Operations"

[ISO/IEC TR 24772-2013]Buffer Overflow in Heap [XYB]
Buffer Overflow in Stack [XYW]
Unchecked Array Indexing [XYZ]
[Meyers 01]Item 30, Make sure destination ranges are big enough"Make Sure Destination Ranges Are Big Enough"

 

...