Pages

When an iterator is not dereferencable

Say that I am using an STL container (for instance, a queue) in your code. Somewhere I want to get an element from it, calling front(). Say that I forget to check if there is actually anything in it before grabbing it, and I am so unluck to find out that it is empty. What it is going to happens?

Accordingly to the C++ standard, no one knows. It is one of those undefined behavior that should worry you so much to be very careful in writing C++ code.

If you are developing on Visual Studio, and you application is built in debug mode, the disaster is shielded by an assertion failure that pops up a window with some debug information that should help you to find the offending line (just press the retry button, and debug your code).

If you want to see what happens in these cases, you could try this code:
#include <queue>

// ...
void f()
{
// ...
    std::queue<int> qi;

//    qi.front(); // deque iterator not dereferencable
//    qi.pop(); // deque empty before pop

// ...
}
1. If you uncomment this line, you would get a "deque iterator not dereferencable" assertion, since you are trying to dereference an iterator to an empty queue.
2. Trying to popping an empty queue results in a "deque empty before pop" assertion.

[edit: Jon commented on google plus to this post, adding information for g++ and STLport. It is a very long time since the last time I have used the latter, but g++ is everyday matter, and Jon is right, I'd better complete the discussion with some words on the behavior of the Free Software Foundation compiler]

To check what happens on g++, compile the code in debug mode, defining the constant _GLIBCXX_DEBUG, and run the resulting application.

For both call you will get the same error message, "attempt to access an element in an empty container.", the execution will be aborted, and you will get some information on the objects involved in the operation.

Go to the full post