0

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);
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
pepero
  • 7,095
  • 7
  • 41
  • 72

1 Answers1

4

Take a look at this line:

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

Try to use the proper iterator for erase:

rest.erase(rest.begin()+i);
Ionut
  • 6,436
  • 1
  • 17
  • 17
  • great, lonut, this solves the crash!! but is this a bug or some pitfalls from stl? – pepero Sep 12 '13 at 15:03
  • By definition `erase` removes the element pointed to by the iterator you pass to it as a parameter. So normally that iterator should point to an element from the vector you're erasing from, not to an element from another vector. You're not getting a compile error because in this case the types match, both are `std::vector::iterator`s, but it is a bug to do this. – Ionut Sep 12 '13 at 15:27