Search code examples
c++vectorstliteratorerase

Segfault when erasing from vector while in nested loops


This is the code I'm running:

for(auto candidate = candidates.begin(); candidate != candidates.end();) {
    for(auto inst = candidate->sortedLoads.begin(); inst != candidate->sortedLoads.end(); inst++) {
        if(...) {
            candidate = candidates.erase(candidate);
            break;
        }

        else {
            candidate++;
        }
    }        
}

Running into a segfault with above. If I remove the inner for-loop the segfault goes away. Do you guys know what's wrong?


Solution

  • EDIT
    You're incrementing your candidate variable from the outer loop in the inner loop, where nothing prevents him to exceed its upperbound candidate != candidates.end(). Add at least that condition to your inner loop as well. You'll end up with:

    for(auto candidate = candidates.begin(); candidate != candidates.end();) {
        for(auto inst = candidate->sortedLoads.begin(); candidate != candidates.end() && inst != candidate->sortedLoads.end() ; inst++) {
            if(...) {
                candidate = candidates.erase(candidate);
                break;
            }
    
            else {
                candidate++;
            }
        }
    }
    

    But in general if you would increment/decrement (or whatever operation that changes value) a loop variable inside another loop, you need to repeat the first loop condition(where the variable is coming from) in the second loop (where it's being changed)!