You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的C语言哈希表销毁代码中是否存在Heap-use after free问题?

解决哈希表销毁函数中的Heap-use after free问题

你的核心问题出在ht_destroy函数的free(&ht->list[i])这一行,这是完全错误的内存释放操作:

错误原因

在ht_create里,ht->list是通过一次malloc分配的连续内存块,大小为2^hash_length * sizeof(struct llist),数组里的每个struct llist元素都是这片连续内存的一部分,并不是单独用malloc分配的独立对象。调用free(&ht->list[i])相当于尝试释放堆内存中某个连续块的局部地址,属于非法操作,会直接破坏堆结构,进而引发Heap-use after free这类内存错误。

修正后的销毁函数

void ht_destroy(struct hashtable *ht) {
  // 提前计算表大小,避免循环内重复计算
  int table_size = my_exp(2, ht->hash_length);
  for(int i = 0; i < table_size; ++i) {
      struct llnode *curnode = ht->list[i].front;
      struct llnode *nextnode = NULL;
      // 释放当前链表的所有节点
      while (curnode) {
        nextnode = curnode->next;
        free(curnode->str);
        free(curnode);
        curnode = nextnode;
      }
      // 注意:这里不需要释放ht->list[i],它是数组的一部分
  }
  // 一次性释放整个链表数组的内存
  free(ht->list);
  // 最后释放哈希表结构体本身
  free(ht);
}

额外优化说明

  1. 提前计算table_size,避免在循环中重复调用my_exp,减少不必要的计算开销
  2. 直接访问ht->list[i].front,省去了多余的lst指针,简化代码逻辑

修改后运行你的测试代码,堆内存错误会完全消失,所有动态分配的内存(哈希表结构体、链表数组、链表节点、节点字符串)都会被正确释放。

内容的提问来源于stack exchange,提问作者ChildrensBlood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:20:30