That moment when you need to look up definition of C++ for loop

I was getting a segfault on an old piece of code which I maintain. The culprit was pinpointed to this:

bool found = false;
vector<string> :: iterator i;
for (i = v.begin(); !found && i != v.end(); ++i) {
    if (name == *i) {
        found = true;
if (found) {
   v.erase( i ); // <-- segfault here

I went through this piece if code at least 10 times without noticing the problem. The snippet is simple enough.. when match is found, set found to true and that breaks the loop since loop condition now evaluates to false. The iterator remains at the position of matched element.


What we are actually getting is iterator+1.

What we don't see directly from the code is that increment happens before the condition is evaluated for the next loop, giving us iterator+1 which causes a segfault if match is found on last element.