C语言链表问题:仅打印首节点,求错误排查及内存释放方法
问题分析与解决方案
一、链表仅能打印第一个节点的原因
你的代码里链表指针连接逻辑完全错误,导致实际链表只有head一个节点,second和third根本没被接入链表:
- 原本
head->next = second是正确的,但紧接着你又写了head->next = third,直接覆盖了head的后继节点,跳过了second; - 最后你再写
head->next = NULL,直接把head的后继置空,等于链表彻底只剩head自己。
正确的链表连接逻辑应该是:
head的next指向secondsecond的next指向thirdthird的next指向NULL(标记链表结尾)
修正后的main函数关键代码:
head->data = 10; head->next = second; second->data = 20; second->next = third; // 给second的后继赋值,而非修改head的后继 third->data = 30; third->next = NULL; // 最后一个节点的后继置空
二、malloc内存释放的时机与方法
内存释放要在你完全不再需要使用链表之后执行,也就是打印完链表之后。如果提前释放,后续访问链表会触发野指针错误。
你可以选择两种方式处理:
方法1:编写专门的释放函数
void freeList(struct Node *ptr) { struct Node *temp; while (ptr != NULL) { temp = ptr; ptr = ptr->next; free(temp); } }
然后在main函数的printList(head);之后调用:freeList(head);
方法2:直接在main函数内处理
printList(head); // 遍历释放内存 struct Node *temp; while (head != NULL) { temp = head; head = head->next; free(temp); }
完整修正后的代码
#include<stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void printList(struct Node *ptr); void freeList(struct Node *ptr); int main(void) { struct Node* head = NULL; struct Node* second = NULL; struct Node* third = NULL; head = (struct Node*)malloc(sizeof(struct Node)); second = (struct Node*)malloc(sizeof(struct Node)); third = (struct Node*)malloc(sizeof(struct Node)); head->data = 10; head->next = second; second->data = 20; second->next = third; third->data = 30; third->next = NULL; printList(head); freeList(head); } void printList(struct Node *ptr) { struct Node *listPtr = ptr; int count = 1; if (listPtr == NULL) { printf("No elements in list.\n"); return; } while (listPtr!=NULL) { printf("element %d = %d\n",count,listPtr->data); listPtr = listPtr->next; count++; } } void freeList(struct Node *ptr) { struct Node *temp; while (ptr != NULL) { temp = ptr; ptr = ptr->next; free(temp); } }
内容的提问来源于stack exchange,提问作者dynamitri
相关产品推荐
相关产品推荐

