c - 非常短的代码,但是,未能释放内存

标签 c linux hashtable glib

首先,我插入 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/

相关文章:

c - 在两个哈希表之间移动项目

r - 如何通过迭代列来创建字典/哈希表?

linux - 在 ubuntu 18.04 上更新后无法打开 libmpfr.so.4

c# - 在 .NET 哈希表(或其他结构)中获取最接近/下一个匹配项

c - 如何将一个指针指向的地址分配给另一个本地指针

c - 应用程序请求与 Linux 内核响应的在线匹配

linux - ubuntu 内核在 OOPS 上挂起而没有在 dmesg 或/var/log/kern.log 中显示堆栈跟踪

linux - 调用具有用户界面的外部程序的 Shell 脚本

c - 使用 Visual HAM 在 C 中进行 GBA 编程

c - _chsize 在 vi​​sual studio 2017 上引发断言错误