C语言链表尾添加新节点出现段错误,请求排查问题
段错误原因分析与修复方案
你的代码触发段错误的直接原因是add_node函数末尾的两行代码:
int *x = NULL; *x = 5;
这里x被初始化为空指针(指向内存地址0),对空指针进行解引用操作*x = 5属于未定义行为——程序试图往系统不允许访问的内存地址写入数据,直接触发段错误。
你的链表添加逻辑本身是正确的,只需删除这两行无关代码,程序就能正常运行。另外建议给malloc添加失败检查,避免内存分配失败后操作空指针引发新问题,修复后的完整代码如下:
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; struct node *head = NULL; void add_node(int data) { struct node *new_node = malloc(sizeof(struct node)); // 添加malloc失败检查 if (new_node == NULL) { perror("malloc failed"); return; } new_node->data = data; new_node->next = NULL; if (head == NULL) { head = new_node; } else { struct node *current = head; while (current->next != NULL) { current = current->next; } current->next = new_node; } } int main() { add_node(5); // 可选:打印链表验证功能 struct node *current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } return 0; }
内容的提问来源于stack exchange,提问作者James Demisse
相关产品推荐
相关产品推荐

