2013-08-17 17 views
0

首先,我插入鑰匙= STR1,值= header_buff非常短的代碼,但是,未能釋放內存

其次,我用STR2查找指針

第三,我釋放指針,我的malloc 'd,但失敗了。爲什麼?

#include <stdio.h> 
#include <glib.h> 
int main() 
{ 
    GHashTable *hash; ///define my hashtable 

    char str1[20] = "key"; 
    char str2[20] = "key"; 

    char *header_buff = (char*) malloc(sizeof(char) * 1024 * 1024); 
    memcpy(header_buff, "value", 5); 
    printf("%p\n", header_buff); 

    hash = g_hash_table_new(g_str_hash, g_direct_hash); ///here I use (g_str_hash, g_direct_hash) 
    g_hash_table_insert(hash, str1, header_buff); /// insert the str1 as key 

    char * c = (char*) g_hash_table_lookup(hash, str2); ///use str2 to find the value 
    if (c) 
    { 
    printf("%s\n", c); ///can print the string "value" 
    printf("%p\n", c); 
    free(c); ///the same address? but I can't free the mem! 
    c = NULL; 
    } 
    return 0; 
} 
+4

將'#include '添加到您的包含文件列表中,並**從'malloc()'返回值**中刪除該強制轉換。 [看到這個問題爲什麼](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)。 – WhozCraig

+2

[參考'g_hash_table_lookup'](https://developer.gnome.org/glib/2.36/glib-Hash-Tables.html#g-hash-table-lookup)沒有提到需要釋放指針返回。相反,你應該釋放你實際分配的指針。 –

+1

此外,不應該從'malloc'或'g_hash_table_lookup'投出返回。 –

回答

-1

瘋狂的猜測是你在你的平臺上缺少#include和sizeof(int)!= sizeof(void *)。

+0

介紹說明,我沒有看到爲什麼這應該與一個鍵未能查找其關聯值(如果sizeof(int)第二種情況會導致正式的信息減少,這會在'insert'和'lookup'上發生,因此不會產生問題(與使用全長密鑰相比,存儲桶分佈可能會發生變化,但對於API enduser) – drahnr

3

從文檔:

GHashTable *  g_hash_table_new (GHashFunc hash_func, 
             GEqualFunc key_equal_func); 

所以,你正在使用兩個哈希功能,而不是一個哈希一個平等功能,這反過來將無法正常工作。

這是它應該看起來。

table = g_hash_table_new (g_str_hash,g_str_equal); 

請注意,如果你不包含但相同字符的字符串使用的相同實例g_direct_*可能無法正常工作。它會直接比較gchar指針

+0

+1用於指出hasher和api的比較器要求之間的區別我不熟悉google api,但是你的邏輯看起來很合理直接比較器的註釋也很有幫助。 – WhozCraig