C语言实现哈希表插入节点时触发Segmentation Fault问题
故障原因
段错误触发的核心是空指针解引用:
- 初始化哈希表时,你通过循环把指针数组
table的所有元素都赋值为NULL,此时table[0]本身就是空指针,不指向任何有效的node结构体内存。 - 你错误地把
table[0]当成了预先存在的链表哨兵节点,执行table[0]->next时,相当于从内存地址0处读取next成员的值,这块内存不属于程序可访问范围,直接被操作系统拦截触发段错误。 - 额外逻辑偏差:
table是node*类型的指针数组,每个数组元素存储的是对应索引桶的链表头节点地址,本身不是节点,不需要提前嵌套一层next访问。
修复方案
调整链表头插逻辑,不需要额外访问table[0]的成员:
- 新节点的
next直接指向当前table[0]存储的头节点地址(空链表时这个值就是NULL,刚好符合链表尾节点的next取值要求) - 再把
table[0]更新为新节点的地址,完成头插 - 补充
malloc返回值校验,避免内存分配失败导致的异常;实际使用时记得用完释放链表内存,避免内存泄漏。
修复后可运行代码
#include <cs50.h> #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { typedef struct node { char *word; struct node *next; } node; const unsigned int N = 10; node *table[N]; for (int i = 0; i < N; i++) { table[i] = NULL; } char *words[] = {"Hell", "Sup", "Brain", "Greek", "Mother", "Flip", "Poster", "Dark", "Apple", "Kandy"}; for (int i = 0; i < 10; i++) { char *wordle = words[i]; node *n = malloc(sizeof(node)); if (n == NULL) { printf("内存分配失败,程序退出\n"); return 1; } n->word = wordle; // 修正后的头插逻辑 n->next = table[0]; table[0] = n; printf("%s\n", table[0]->word); } // 释放链表内存,避免泄漏 node *cursor = table[0]; while (cursor != NULL) { node *tmp = cursor; cursor = cursor->next; free(tmp); } return 0; }
内容的提问来源于stack exchange,提问作者Sarthak Hingankar
相关产品推荐
相关产品推荐

