2012-03-26 80 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