2012-10-03 124 views
0

我試圖將malloc'd字符串作爲鍵和結構添加爲值。每次都是一個新的字符串,但有時文本是相同的,所以他們應該被視爲相同的密鑰。添加結構後,我嘗試檢索它,但不成功(下面的「失敗的添加」)。此外,我的總數沒有得到更新,並且當銷燬電話免費時,我就會發生故障。現在我已經評論了免費。GLib哈希表 - 無法查找鍵/值

GHashTable *heavyhitter= g_hash_table_new_full(NULL, g_str_equal, (GDestroyNotify) free_hh_key,(GDestroyNotify) free_hh_metadatarecords); 
... 
//Called multiple times: 
void add_to_heavyhitter_hashtable(struct memory *mem, const char *file,int line, size_t sz) { 
struct hh_metadata_record *hh_metadata_record_toadd; 

char *orig_key; 
asprintf(&orig_key, "%s:%d", file, line); 
char *effective_key = orig_key; 

gpointer e_key_ptr = &effective_key; 
gpointer hh_meta_ptr = &hh_metadata_record_toadd; 

if (g_hash_table_lookup_extended(mem->heavyhitter_hashtable, &orig_key, 
     &e_key_ptr, &hh_meta_ptr)) { 
    printf("found\n"); 
    hh_metadata_record_toadd = hh_meta_ptr; 
    printf("hh_metadata_record_toadd sz: %Zu\n", hh_metadata_record_toadd->sz); 
} else { 
    printf("not found\n"); 
    hh_metadata_record_toadd = hh_get_metadata_record_new(sz); 

} 

printf("Effective Key: %s\n", effective_key); 

hh_metadata_record_toadd->count += 1; 
hh_metadata_record_toadd->sz += sz; 
mem->hh_total_count += 1; 
mem->hh_total_size += sz; 

g_hash_table_insert(mem->heavyhitter_hashtable, e_key_ptr, 
     hh_metadata_record_toadd); 
if(g_hash_table_lookup_extended(mem->heavyhitter_hashtable, effective_key, NULL, NULL)) 
    printf("Succesfully added.\n"); 
else 
    printf("Failed add\n"); 
printf("hash Table size: %Zu\n",g_hash_table_size(mem->heavyhitter_hashtable)); 

免費功能註釋掉現在:

void free_hh_key(gpointer a) { 
    (void) a; 
    printf("Freeing: %s\n", (char*) a); 
    //free(a); 
} 

結果:

not found 
Effective Key: hhtest.c:49 
Failed add 
hash Table size: 1 
not found 
Effective Key: hhtest.c:49 
Freeing: �' �' �' �/Y� 
Failed add 
hash Table size: 1 
not found 
Effective Key: hhtest.c:10 
Freeing: �' �' �' �/Y� 
Failed add 
hash Table size: 1 
+0

爲什麼你創建空的哈希表進行hash_func?你的代碼非常難以閱讀,考慮在問一個這樣的問題時,在易於閱讀的測試用例中隔離有問題的代碼。 – Ancurio

回答