首先,我插入 key=str1,value=header_buff
其次,我使用str2来查找指针
第三,我释放了我分配但失败的指针。为什么?
#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;
}
最佳答案
来自文档:
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
指针!
关于c - 非常短的代码,但是,未能释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18292348/