C语言链表打印异常:替换插入位置后输出结果不符的原因
问题分析:链表插入后输出异常的原因
原代码
#include<stdio.h> #include<stdlib.h> typedef struct Node{ int value; struct Node *next; }Node; Node *create_node(int value){ Node *p=malloc(sizeof(Node)); p->value=value; p->next=NULL; return p; } void *insert_at_head(Node **head,Node *node){ node->next=*head; *head=node; } void insert_after_node(Node *node_to_insert_after,Node *new_node){ new_node->next=node_to_insert_after->next; node_to_insert_after->next=new_node; } void printlist(Node *head){ Node *tmp=head; while(tmp!=NULL){ printf(" %d",tmp->value); tmp=tmp->next; } } Node *find_node(Node *head,int value){ Node *tmp=head; while(tmp!=NULL){ if(tmp->value==value) return tmp; tmp=tmp->next; } return NULL; } int main(){ Node *head; Node *tmp; for(int i=0;i<25;i++){ tmp=create_node(i); insert_at_head(&head,tmp); } tmp=find_node(head,24); insert_after_node(tmp,create_node(75)); printlist(head); return 0; }
问题描述
运行上述代码时,输出结果为24 75 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0,但将语句insert_after_node(tmp,create_node(75));替换为insert_after_node(head,create_node(75));后,输出仅为24 75 23,请问这是什么原因?
原因分析
核心问题出在insert_at_head函数的返回类型定义错误:
- 该函数被声明为
void *类型(需返回空指针),但函数体内没有任何return语句返回指针值,违反C语言标准,触发未定义行为。 - 未定义行为的表现具有随机性:第一次运行时编译器的偶然行为让链表后续节点指针暂时正常;修改插入目标为
head后,未定义行为的影响显现,导致23节点的next指针变为无效值(如野指针或NULL),printlist遍历到23就停止。
另外还有潜在问题:main函数中Node *head;未初始化,第一次调用insert_at_head时访问野指针*head,同样属于未定义行为,加剧了链表结构的破坏。
修复方案
- 将
insert_at_head的返回类型改为void(该函数无需返回值):
void insert_at_head(Node **head,Node *node){ node->next=*head; *head=node; }
- 初始化
head为NULL,避免野指针访问:
int main(){ Node *head = NULL; Node *tmp; // 其余代码不变 }
修改后,无论使用哪种插入方式,都会输出完整的链表:24 75 23 22 ... 0。
内容的提问来源于stack exchange,提问作者Tachfine Houssame
相关产品推荐
相关产品推荐

