首先,我插入鑰匙= 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;
}
將'#include'添加到您的包含文件列表中,並**從'malloc()'返回值**中刪除該強制轉換。 [看到這個問題爲什麼](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)。 –
WhozCraig
[參考'g_hash_table_lookup'](https://developer.gnome.org/glib/2.36/glib-Hash-Tables.html#g-hash-table-lookup)沒有提到需要釋放指針返回。相反,你應該釋放你實際分配的指針。 –
此外,不應該從'malloc'或'g_hash_table_lookup'投出返回。 –