C语言哈希表load函数调试:链表节点指针无法正确更新
哈希表Load函数调试问题解析
问题背景
学习C语言期间调试文本拼写检查程序的哈希表load函数时遇到问题:函数能正常读取字典文件中的单词并分配临时node*节点,但无法将struct node* table[]正确指向临时节点;哈希函数工作正常,排除其问题。补充测试发现,执行new_word->next = table[index];后,table[index]->next地址始终为0x00,单链表的下一个节点指针无法更新。
问题代码
bool load(const char *dictionary) { // 打开字典文件 FILE *dict = fopen(dictionary, "r"); if (dict == NULL) { printf("Error opening dictionary file.\n"); return 1; } // 分配内存存储当前单词 char *current_word = malloc(LENGTH * sizeof(char)); if (current_word == NULL) { printf("Error in allocating memory.\n"); return 1; } // 初始化哈希索引和单词计数器 int index; int count = 0; while (fgets(current_word, LENGTH, dict) != NULL) { // 为新单词分配节点内存 node *new_word = malloc(sizeof(node)); if (new_word == NULL) { printf("Error allocating memory.\n"); return 1; } // 将单词复制到节点,更新链表头 strcpy(new_word->word, current_word); index = hash(new_word->word); new_word->next = table[index]; table[index] = new_word; free(new_word); count++; } }
问题根源与修复方案
- 核心问题:代码在将
new_word挂载到哈希表的链表头部后,立刻调用free(new_word);释放了节点内存。这导致table[index]指向的是已被释放的无效内存,后续对链表的所有操作都会出现异常,包括next指针无法正常更新。 - 修复步骤:
- 删除
free(new_word);语句。哈希表的节点需要持续存在以支持后续拼写查询,不能在挂载后立即释放。 - 处理
fgets读取的换行符:fgets会把换行符一同读入current_word,导致存储的单词包含多余换行符。可在复制到节点前添加current_word[strcspn(current_word, "\n")] = '\0';截断换行符。 - 完善函数收尾:在
while循环结束后,添加fclose(dict); free(current_word); return true;,完成文件关闭、临时内存释放和正确返回值。
- 删除
内容的提问来源于stack exchange,提问作者Charlie Webster
相关产品推荐
相关产品推荐

