C语言链表查询节点指针时触发段错误(core dumped)求助
问题分析与解决方案
核心错误原因
你的代码触发段错误(Speicherzugriffsfehler)的直接原因是空指针非法引用,根源在于遍历链表时破坏了全局链表头指针:
在main函数的遍历打印环节,你直接修改了全局变量list:
while (list != NULL) { printf("Node %s mit Key %d\n", list->value, list->key); list = list->next; }
遍历结束后,list会被置为NULL(链表最后一个节点的next字段本身就是NULL)。此时调用get(list, 4000)相当于传入NULL,get函数会直接返回NULL,后续尝试访问n->key就是对空指针的非法内存访问,最终触发段错误。
修复步骤
- 使用临时指针遍历链表,保留原头指针
修改main中的遍历代码,用临时变量代替全局list进行遍历,避免破坏原链表的头指针:
int main(void) { list = add(list, 3000, "Bern"); list = add(list, 4000, "Basel"); list = add(list, 8000, "Zurich"); // 使用临时指针temp遍历,不修改全局list struct node *temp = list; while (temp != NULL) { printf("Node %s mit Key %d\n", temp->value, temp->key); temp = temp->next; } struct node *n = get(list, 4000); // 增加空指针判断,避免后续访问出错 if (n != NULL) { printf("Key is: %d \n", n->key); } else { printf("Node with key 4000 not found\n"); } }
- 优化
get函数(可选)
原get函数的返回逻辑冗余,循环结束后如果n不为NULL,则必然满足n->key == key,可以简化为:
struct node *get(struct node *list, int key){ struct node *n = list; while(n != NULL && n->key != key){ n = n->next; } return n; // 找到返回节点,未找到返回NULL }
- 内存泄漏提示(非当前错误,但需注意)
代码中使用malloc分配节点内存,但未做释放操作,长期运行会导致内存泄漏。可以在程序结束前遍历链表,逐个调用free释放节点。
内容的提问来源于stack exchange,提问作者Yasmin
相关产品推荐
相关产品推荐

