Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

ITER.END.DEREF.MUST

Dereference of end iterator

The ITER checkers find problems with iterators in containers. The ITER.END.DEREF.MUST checker flags instances in which an iterator is explicitly checked against the value of the end() or rend() method of the container object, and then dereferenced when its value could be equal to end() or rend().

Vulnerability and risk

Using an invalid iterator typically results in undefined behavior.

Mitigation and prevention

To avoid this issue, add a check to your code to make sure that the iterator isn't equal to the value of end() or rend().

Vulnerable code example

1   #include <set>
2   using namespace std;
3   int foo(set<int>& cont)
4   {
5     int x = 0;
6     set<int>::iterator i;
7     for (i = cont.begin(); i != cont.end(); i++)
8     {
9       x += *i;
10       if (x > 100)
11        break;
12     }
13     x += *i;
14     return x;
15   } 

If no break occurs in the loop at line 9 in this example, the value of iterator 'i' will be equal to cont.end() after the loop. In this case, dereferencing 'i' is invalid, and will produce undefined results.

Fixed code example

1   int foo(set<int>& cont)
2   {
3     int x = 0;
4     set<int>::iterator i;
5     for (i = cont.begin(); i != cont.end(); i++)
6     {
7       x += *i;
8       if (x > 100)
9         break;
10     }

11     if (i != cont.end())
12      x += *i;
13     return x;
14   } 

In the fixed example, the check added at line 11 ensures that iterator 'i' isn't equal to cont.end().

Extension

This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.