0

From what I understand, the following program

#include <map>

int main()
{
    std::map<int,int> foo;
    std::map<int,int>::iterator start = foo.begin();
    while (start++ != foo.end())
        ;
}

should terminate, but it instead loops indefinitely using libstdc++ 4.7.2. Is the behavior exhibited by this program correct, or is there a bug in the standard library? What are the operational properties of operator++(int) on iterators?

ppalka
  • 27
  • 4

1 Answers1

7

The map is empty, so the first start++ is attempting to increment an end iterator which is undefined behaviour. From std::map::end():

Returns an iterator to the element following the last element of the container. This element acts as a placeholder; attempting to access it results in undefined behavior.

Even though the post increment start++ returns the original value of start, which in this case would be end(), it is unreasonable to expect the loop to terminate due to the presence of undefined behaviour.

To correct, check if start is equal to foo.end() before incrementing or dereferencing.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Bonus Question to your answer: So iterators do not have the same behavior than primitives? for int -> i++ returns the old value of i while ++i returns the new value. so start++ should return foo.end() because thats the value before iteration. – cwin May 23 '13 at 16:10
  • 2
    @ChriZzZ, but `start` has still been modified which is undefined behaviour. So expecting the loop to terminate is unreasonable in the presence of undefined behaviour. – hmjd May 23 '13 at 16:12