0
votes
int Celda :: look(int dni)
{
    bool found = false; 
    int i = 0; int pos = -1;
    //tam_ sometimes have a strange value, but I only
    while(i < tam_ && !found){ 
        //touch tam_ in the constructor, is the size of Celda
        if(dni == bloques_[i]){    
           found = true;
            pos = i;
        }
        ++i;
    }
    return pos;
}

In main I call a method of another class that calls other that uses the look method I've copied here. In some cases it works, but other times the program stops giving a segmentation fault.

When I use a debugger, I've created another variable for store the tam_ value (tam_ is int type), and when I reach that line or the while loop (with condition with tam_) sometimes the segmentation fault appears.

The constructor of Celda is:

Celda :: Celda(int tamanio)
{
bloques_ = new int[tamanio];
bloq_ocupados_ = 0;
tam_ = tamanio;
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;
}

class Celda
{
    private:
        int* bloques_;
        int bloq_ocupados_;
        int tam_;

And down the public section

int Tabla :: busq_lineal(int dni) //si pos_dentro acaba valiendo -1, no se encontrĂ³
{
    bool encontrado = false; 
    int pos = hash(dni), comparaciones = 0, pos_dentro, pos_fuera;
    int tamaniotab = nceldas_ * tabla_[0]->gettam();
    while(!encontrado && comparaciones < tamaniotab){
        pos_dentro = tabla_[pos]->buscar(dni);
        if(pos_dentro != -1){ //si lo encuentro...
            encontrado = true;
            pos_fuera = pos;
            comparaciones += pos_dentro + 1;
        }else if(pos < nceldas_ - 1){ //mientras no nos salgamos de la tabla, avanzamos
            ++pos;
            comparaciones += tabla_[0]->gettam();
        }else {
            pos = 0; //si nos salimos, volvemos al principio
            comparaciones += tabla_[0]->gettam();
        }
    }
    return comparaciones;
}
2
It is considered a good practice to use English identifiers. Just an offtopic note. And more ontopic: could we have a testcase? sscce.org - Griwes
Can you post destructor, copy constructor and assignment operator for class Celda? - hmjd
For a segfault to happen in the condition, you'd have to have a bad this pointer. Could you check if this makes sense at the point of crash? - user3458
Show your complete class - Arunmu
@Arkadiy you are right, the debbuger told me somtething about this pointer...what is the solution for that?? - freinn

2 Answers

1
votes

The error is most probably in this line:

int pos = hash(dni);

As you said, your hash function just returns dni % 199. This will work okay, only if you have at least 200 items in your hash table.

-2
votes

Shouldnt it be "i++"?

for(int i = 0 ; i < tam_ ; i++){
    bloques_[i] = 0;
}