ITER.END.OUTPARAM.MUST
Use of 'end' as an output iterator
A defect will be reported for use of an OutputIterator in an STL algorithm that is demonstrably pointing 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
#include <vector>
#include <algorithm>
void noncompliant (std::vector<int> & v)
{
auto it = v.begin ();
if (it == v.end ())
{
std::fill_n (it, 5, 0);
}
}
Klocwork reports defect ITER.END.OUTPARAM.MUST on line 9 stating "Iterator 'it' is passed as an output iterator at line 9 when it can be equal to the value returned by the call to [r]end(). The iterator is compared to [r]end() at the line 7.". Iterator 'it' is used as an OutputIterator to algorithm fill_n, and is demonstrably pointing to the end of container 'v'.
Fixed code example
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.