2012-03-26 81 views
0
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; 
} 

主要我调用另一个类的方法,调用其他类使用我在这里复制的外观方法。在某些情况下,它可以工作,但其他时候程序会停止提供分段错误。C++奇怪的分段错误

当我使用调试器时,我创建了另一个用于存储tam_值(tam_是int类型)的变量,并且当我到达该行或while循环(带有tam_的条件)时,有时会出现分段错误。

Celda的构造是:

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_; 

和向下的公共部分

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; 
} 
+0

使用英文标识符被认为是一种很好的做法。只是一个offtopic笔记。更多ontopic:我们可以有一个测试用例吗? http://sscce.org/ – Griwes 2012-03-26 16:35:42

+0

你可以发布类'Celda'的析构函数,复制构造函数和赋值运算符吗? – hmjd 2012-03-26 16:37:56

+0

为了在条件中发生段错误,你必须有一个糟糕的'this'指针。你能否检查一下'这个'在碰撞的时候是否有意义? – Arkadiy 2012-03-26 16:39:01

回答

1

该错误是最有可能在这一行:

int pos = hash(dni); 

正如你所说,你hash函数只是返回dni % 199。只有在散列表中至少有200个项目时,这才能正常工作。

+0

谢谢你,但我从来没有看过散列法xDDD – freinn 2012-03-26 17:13:33

+0

它可能发生:D – mfontanini 2012-03-26 17:18:07

-2

不应该说,它是 “我++”?

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

我++是比++慢,我做我所有的循环与++我有一点改善的性能 – freinn 2012-03-26 16:38:02

+3

前缀vs后缀是**不**罪魁祸首 – chrisaycock 2012-03-26 16:38:13

+0

前缀(++ i)和后缀(i ++)递增运算符都会增加该值,前缀效率更高,往往是首选。 – tmpearce 2012-03-26 16:39:07