質問

I'm worried about this bug. As far as I read its about new/delete errors, but I'm not sure why this just happens.

Well, here is my base class "algoritmo":

class algoritmo{
  protected:
  int* vector_;
  int n_;
  public:
  algoritmo();
  algoritmo(int);
  ~algoritmo();
  void mostrar();
  virtual void ordenar(int,int,int)=0;}; 

And here is one of her childs "qsort":

class quicksort : public algoritmo{
  public:
  quicksort():algoritmo(){}
  quicksort(int j):algoritmo(j){}
  ~quicksort();
  void ordenar(int,int,int);
}; 

And I do this on main.cpp:

#include <vector>
using namespace std;
int main(void){
   vector<algoritmo*> metodos;
   int tamvector;
   cout << "Size of the vector" << endl;
   cin >> tamvector;
   metodos.push_back(new quicksort(tamvector));
   metodos[0]->mostrar();
   metodos[0]->ordenar(0,tamvector,0);
   cout << "I did";
   metodos[0]->mostrar();
   cout << "I didn't access a wrong pos" << endl;
   cout << metodos.empty();
   return 0;
   }

I don't know why, but if I enter size 9,45,20,11,3 it works fine but when I enter size 10 I get numap or double free or corruption.

May someone explain me why?

Thanks for your attention.

Update: information of classes as requested

`**Algoritmo definition**

algoritmo::algoritmo(){
   n_=0;
   vector_=new int[n_];
}

algoritmo::algoritmo(int tamano){
   n_=tamano;
   vector_=new int[n_];
   srand(time(NULL));
   for(int i=0;i<n_;i++){
      vector_[i]=rand()%9000+1000;
   }
}

algoritmo::~algoritmo(){
   delete vector_;
   n_=-1;
}

void algoritmo::mostrar(){
   for(int i=0;i<n_;i++){
      cout << vector_[i] << " ";
   }
   cout << endl;
}`

And quicksort definition

`quicksort::~quicksort(){}
void quicksort::ordenar(int ini,int fin,int relleno1){
   int i,f,p,x;
   i=ini; 
   f=fin;
   p=vector_[(i+f)/2];   
   while(i < f){
      while(vector_[i]<p)
         i++;
      while(vector_[f]>p)
         f--;
      if(i<=f){ 
         x=vector_[i];
         vector_[i]=vector_[f];
         vector_[f]=x;
         i++;
         f--;
      }
   }
   if(ini <f) 
      ordenar(ini,f,relleno1);
   if(i < fin)
      ordenar(i,fin,relleno1);
}`
役に立ちましたか?

解決

Your class manages a dynamically allocated array, but does not follow the rule of three in that you have not provided a copy constructor or assignment operator that takes care of making copies of the managed resources where applicable. So when you copy or assign, you get more than one instance pointing to the same dynamically allocated array. They all attempt to call delete on it at the end of their lifetime, giving you the double-free error.

You can fix this easily by using an std::vector<int> as data member instead of using a raw pointer to a dynamically allocated array.

Note: there may be other errors, but this particular one is a source of undefined behaviour and should be fixed.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top