链表插入函数空指针判断失效触发段错误问题求助
链表插入函数段错误排查
问题描述
实现链表的position和insertafter函数后,功能基本正常,但输入链表中不存在的元素时,未按预期输出“Insertion not possible”,反而触发段错误。
代码实现
struct node *position(int key) { struct node *p1 = head; while (p1->info != key && p1 != NULL) { p1 = p1->link; } if (p1 == NULL) printf("Insertion not possible"); return p1; } insertafter(int item) { struct node *new = (struct node *)malloc(sizeof(struct node)); struct node *p2 = position(item); int ele; printf("Enter element to be inserted "); scanf("%d", &ele); if (p2 == NULL) printf("Insertion not possible"); else { new->info = ele; new->link = p2->link; p2->link = new; } }
错误原因
核心问题出在position函数的while循环条件顺序:
while (p1->info != key && p1 != NULL)
C语言中逻辑与&&是短路求值,但这里把p1->info != key放在前面。当链表遍历到末尾时,p1会变成NULL,此时先执行p1->info,相当于访问空指针的成员变量,直接触发段错误,程序根本无法进入后续的p1 == NULL判断分支。
修复方案
调整循环条件的顺序,先判断p1是否为空,再访问其成员:
struct node *position(int key) { struct node *p1 = head; // 先判断p1非空,再访问成员 while (p1 != NULL && p1->info != key) { p1 = p1->link; } if (p1 == NULL) printf("Insertion not possible\n"); return p1; }
另外补充两个优化点:
insertafter函数缺少返回值类型,建议显式声明为void:
void insertafter(int item)
- 增加
malloc失败的判断,避免后续空指针操作:
struct node *new = (struct node *)malloc(sizeof(struct node)); if (new == NULL) { printf("Memory allocation failed\n"); return; }
内容的提问来源于stack exchange,提问作者Risher322
相关产品推荐
相关产品推荐

