Search code examples
c++vectorcrashglibc

crash with "glibc detected: vector double free or corruption (out)"


I am implementing a permute function for integers. it has run time error of "vector double free or corruption (out)".

With gdb, after step by step calling, it crashes after the iteration finishes.

But I really struggle to find out where the problem is.

#include <vector>    

using namespace std;

class Permute {
public:  
    vector<vector<int> > vv;

    // interface      
    vector<vector<int> > permute(vector<int> &num) {
        vector<int> v(0);
        doPermute(v, num);     
        return vv;
    }

    // recursive function to permute
    void doPermute(vector<int> v, vector<int> &num) {
        if(num.empty()) {
            vv.push_back(v);          
            // on gdb, if next after the above one, it is fine, 
            // but crashes after the following next  
        } else {
            for (int i = 0; i < num.size(); i++)
            {
                int toAdd = num[i];
                vector<int> rest(num);
                rest.erase(num.begin()+i);                   
                vector<int> prefix(v);
                prefix.push_back(toAdd);
                doPermute(prefix, rest);
            }                
        }
    }        
};

int main(){
    Permute pInst;
    // sample to test with {1}
    vector<int> vt (1, 1);
    pInst.permute(vt);
}

Solution

  • Take a look at this line:

    rest.erase(num.begin()+i);
    

    Try to use the proper iterator for erase:

    rest.erase(rest.begin()+i);