2012-08-07 60 views
2

我在C中實現了一個hashmap,經過相當多的工作後,我得到了一切工作很好......除了我的發佈例程。在C中解散hashmap桶陣列

我的結構是建立像這樣:

struct hashmap_element { 
    int value; 
    int key; 
    int used; 
    struct hashmap_element* next; 
}; 
struct hashmap { 
    int table_size; 
    int current_size; 
    struct hashmap_element* table; 
}; 

而且我目前的非工作的釋放程序是這樣的:它第一次運行後

void hm_release(struct hashmap* hm) { 
    hashmap_element* tmp; 
    hashmap_element* curr_itr; 
    for(int x=0; x<hm->table_size; x++) { 
     curr_itr = &hm->table[x]; 
     while (curr_itr) { 
      tmp = curr_itr->next; 
      free(curr_itr); 
      curr_itr = tmp; 
     } 
    } 
    free(hm->table); 
    free(hm); 
} 

不幸的電流segvaults。我似乎無法讓我的'curr_itr'鎖定到陣列中每個桶的第一個鏈上。我在C中使用像這樣的動態內存相當新,而且現在已經停留了幾天。

據我所知,一切正在正確初始化。這裏例如是我的hashmap init函數。

hashmap* hm_initialize() { 
    hashmap* hm = malloc(sizeof(hashmap)); 
    hm->table = (hashmap_element*) calloc(INIT_SIZE, sizeof(hashmap_element)); 
    hm->table_size = INIT_SIZE; 
    hm->current_size = 0; 

    // init the buckets 
    for (int x=0; x < hm->table_size; x++) { 
     hm->table[x].used=0; 
     hm->table[x].value=0; 
     hm->table[x].key=0; 
     hm->table[x].next=NULL; 
    } 
    return hm; 
} 

任何建議/意見將不勝感激。如果您需要更多我的代碼,請讓我知道。

謝謝。

回答

3

你開始得太早釋放,

for(int x=0; x<hm->table_size; x++) { 
    curr_itr = &hm->table[x]; 
    while (curr_itr) { 
     tmp = curr_itr->next; 
     free(curr_itr); 
     curr_itr = tmp; 
    } 
} 

hashmap_elementhm->table[x]不是malloc版,所以你不應該free它。

for(int x=0; x<hm->table_size; x++) { 
    curr_itr = hm->table[x].next; 
    while (curr_itr) { 
     tmp = curr_itr->next; 
     free(curr_itr); 
     curr_itr = tmp; 
    } 
} 

在桶中的第一後釋放只有(希望)mallochashmap_element編號第

+0

我認爲將表作爲指針數組會更好,這樣所有'hashmap_elements'都可以被視爲相同。然後'used'標誌可以被移除,因爲不用的元素只是從表格中移除。 – JeremyP 2012-08-07 15:46:13

+0

謝謝你的幫助,儘管我不得不使用curr_itr = hm-> table [x] .next而不是curr_itr = hm-> table [x] - > next。 – insultant 2012-08-07 15:46:35

+0

@insultant糟糕,當然,'hm-> table [x]'不是指針。 – 2012-08-07 15:53:28