...
In this noncompliant example, the two iterators that delimit the range point into the same container, but the first iterator does not precede the second. On each iteration of its internal loop, std::for_each()
compares the first iterator (after incrementing it) with the second for equality, and as ; as long as they are not equal, it will continue to increment the first iterator. Incrementing the iterator representing the past-the-end element of the range results in undefined behavior.
...
In this compliant solution, the iterator values passed to std::for_each()
are passed in the proper order:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <algorithm> #include <iostream> #include <vector> void f(const std::vector<int> &c) { std::for_each(c.begin(), c.end(), [](int i) { std::cout << i; }); } |
...
In this compliant solution, the proper iterator generated by a call to end()
is passed:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <algorithm> #include <iostream> #include <vector> void f(const std::vector<int> &c) { std::for_each(c.begin(), c.end(), [](int i) { std::cout << i; }); } |
...
Using an invalid iterator range is similar to allowing a buffer overflow, which can lead to an attacker running arbitrary code.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CTR53-CPP | High | Probable | High | P6 | L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Astrée |
| overflow_upon_dereference | |||||||
CodeSonar |
| LANG.MEM.BO | Buffer Overrun | ||||||
Helix QAC |
| C++3802 | |||||||
Parasoft C/C++test |
| CERT_CPP-CTR53-a | Do not use an iterator range that isn't really a range | |||||||
Polyspace Bug Finder |
| CERT C++: CTR53-CPP | Checks for invalid iterator range (rule partially covered). | ||||||
PVS-Studio |
| V539, V662, V789 |
Related Vulnerabilities
In Fun with erase(), Chris Rohlf discusses the exploit potential of a program that calls vector::erase()
with invalid iterator ranges [Rohlf 2009].
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ Coding Standard | CTR51-CPP. Use valid references, pointers, and iterators to reference elements of a container CTR57-CPP. Provide a valid ordering predicate |
Bibliography
[ISO/IEC 14882-2014] | Clause 24, "Iterators Library" |
[Meyers |
2001] | Item 32, "Follow Remove- |
Like Algorithms with erase If You Really Want to Remove Something" |
...
...