2013-10-27 42 views
1

我正在實現一個has_delete函數以及clear_table函數的哈希表。現在我收到有關remove_entry函數的內存讀取錯誤。並幫助將不勝感激正確刪除鏈接列表中的元素?內存錯誤與指針

這是我的結構:

typedef struct bucket { 
    char *key; 
    void *value; 
    struct bucket *next; 
} Bucket; 

typedef struct { 
    int key_count; 
    int table_size; 
    void (*free_value)(void *); 
    Bucket **buckets; 
} Table; 

這裏是我的功能:

int remove_entry(Table * table, const char *key){ 
    unsigned int hc = 0; 
    Bucket *curr_b; 
    Bucket *next_b; 

    if(table == NULL || key == NULL){ 
     return FAIL; 
    } else { 
     hc = hash_code(key)%(table->table_size); 
     if(table->buckets[hc] != NULL){ 
      curr_b = table->buckets[hc]; 

      /*Check the buckets in linked list*/ 
      while(curr_b != NULL){ 
       next_b = curr_b->next; 

       if(strcmp(curr_b->key,key) == 0){ 
        free(curr_b->key); 
        if(table->free_value != NULL){ 
         table->free_value(curr_b->value); 
        } 
        free(curr_b); 
        curr_b = NULL; 
        table->key_count--; 
        return SUCC; 
       } else { 
        curr_b = next_b; 
       } 
      } 
      return FAIL; 
     } 
     return FAIL; 
    } 
} 

內存泄漏來刪除的條目,並嘗試後讀取表後。我認爲我沒有把事情做對。

內存錯誤:

無法弄清楚如何從終端複製/粘貼,所以他們都說像

Invalid read of size __ 
Address ____ is __ bytes inside a block of size ___ free'd 
+2

調試器,努力工作。 –

回答

1

事情你需要考慮在哪裏table->buckets[hc]爲您免費桶的情況下。

權利之前free(curr_b->key);地址:

if(curr_b == table->buckets[hc]) { 
    table->buckets[hc] = next_b; 
} 

因爲它是現在,你免費一斗,但table->buckets[hc]仍然指向它。所以下次你讀它時,你正在閱讀free'ed的記憶。因此錯誤。

另外,您需要跟蹤以前的存儲分區,以便您可以在刪除存儲分區時將上一個存儲分區指向下一個存儲分區。