Is Undefined Behavior To Using Invalid Iterator?

Solution 1:

There is no key comparing equal to "another" in the map. Therefore map.find("another") will return the .end() iterator of the map. Dereferencing this iterator in ->second is then undefined behavior since end iterators may not be dereferenced.

Your code should check that the iterator returned from find is not the end iterator, i.e. that an element has been found.

In terms of debugging, if you are using libstdc++ as standard library implementation (which is the case with GCC and potentially with Clang), you can use -D_GLIBCXX_DEBUGon the compiler invocation to enable debug assertions in the standard library implementation which will detect this issue.