ITER.END.OUTPARAM.MIGHT

Use of 'end' as an output iterator

A defect will be reported for use of an OutputIterator in an STL algorithm that may point to the end of its container. The list of STL algorithms accepting an OutputIterator is as follows:

algorithm argument number
adjacent_difference 3
copy 3
copy_if 3
copy_n 3
exclusive_scan 3
fill_n 1
generate_n 1
inclusive_scan 3
merge 5
move 3
partial_sum 3
remove_copy 3
remove_copy_if 3
replace_copy 3
replace_copy_if 3
reverse_copy 3
rotate_copy 4
set_difference 5
set_intersection 5
set_symmetric_difference 5
set_union 5
transform 3
transform_exclusive_scan 3
transform_inclusive_scan 3
unique_copy 3

Vulnerability and risk

Buffer overflow is the most common security vulnerability, and this defect is a subclass of that vulnerability: C++ STL specific.

Vulnerable code example

Copy
#include <vector>
#include <algorithm>
 
void noncompliant (std::vector<int> & v)
{
  auto it = v.begin ();
  std::fill_n (it, 5, 0);
}

Klocwork reports defect ITER.END.OUTPARAM.MIGHT on line 7 stating "Iterator 'it' is passed as an output iterator at line 7 when it can be equal to value returned by call to [r]end().". Iterator 'it' is used as an OutputIterator to algorithm fill_n, and may point to the end of container 'v'.

Fixed code example

Copy
void compliant (std::vector<int> & v)
{
  auto it = v.begin ();
  if (it != v.end ())
  {
    std::fill_n (it, 5, 0);
  }
}

A guard has been introduced to ensure iterator 'it' is never pointing to the end of container 'v', when passed to algorithm fill_n.