Search code examples
c++arraysdelete-operator

Errors when a destructor deletes an array


class Celda
{
private:
    int* bloques_;
public:
    Celda(int size);
    ~Celda(){ delete [] bloques_; };
};
Celda :: Celda(int size)
{
    bloques_ = new int[size];
    bloq_ocupados_ = 0;
    tam_ = size;
    for(int i = 0 ; i < tam_ ; ++i){
        bloques_[i] = 0;
    }
}

Tabla :: Tabla(int numcel, int tambloq)
{
    nceldas_ = numcel; tam_bloque_ = tambloq;
    tabla_ = new Celda*[nceldas_];
    for(int i = 0 ; i < nceldas_ ; ++i){
        tabla_[i] = new Celda(tam_bloque_);
}
    ocupadas_ = 0;
}

Tabla :: ~Tabla()
{
    for(int i = 0 ; i < nceldas_ ; ++i){
        delete [] tabla_[i];
    }
    delete [] tabla_;
}

I have this coded now, 2 classes, Celda and Tabla, and when I run my program it puts at the end:

* glibc detected: free(): invalidad pointer: 0x0000000002391338 *

The debugger stop deleting bloques_ pointer too many times (like 30) calling the destructor I think.

What is my error??


Solution

  • The uses of new/new[] must match the uses of delete/delete[].

    The tabla_[i] are allocated with new but freed with delete[].

    Change it to

     delete tabla_[i];
    

    and it will work.