Reputation: 1079
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;
}
Upvotes: 0
Views: 238
Reputation: 21900
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.
Upvotes: 1
Reputation: 393
Shouldnt it be "i++"?
for(int i = 0 ; i < tam_ ; i++){
bloques_[i] = 0;
}
Upvotes: -2