C语言中从单链表改造为链表数组后存储异常的调试
C语言链表数组修改后存储逻辑异常问题排查
问题背景
- 原有单个单链表运行正常,需求调整为链表数组结构后,数据存储逻辑不符合预期,现有实现代码如下:
#include <stdio.h> #include <stdlib.h> struct node { int coeff; int power; struct node* Next; }; void Insert(int X,int Y, struct node* L, struct node* P) { struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); temp->coeff = X; temp->power = Y; temp->Next = P->Next; P->Next = temp; } void PrintList(struct node* L) { struct node* P = L; printf("%d %d ",P->coeff,P->power); printf("\n"); P=P->Next; } int main() { struct node* head[3] ; for(int q =0 ; q!= 3 ; q++) { head[q] = malloc(sizeof(struct node)); } Insert(1,2,head[0],&head[0]); Insert(2,3,head[0],&head[0]); Insert(1,2,head[1],&head[1]); Insert(2,2,head[1],&head[1]); for(int i=0 ;i!=3;i++){ PrintList(head[i]); } return 0; }
代码核心问题
- 参数类型不匹配导致非法内存访问:调用
Insert时传入的第四个实参是&head[0](struct node**类型,指向链表头指针的指针),但形参P声明为struct node*(普通节点指针),解引用P->Next时直接读写错误内存,是存储逻辑异常的核心原因。 - Insert函数设计冗余且逻辑错误:形参
L完全未被使用,插入逻辑的操作对象错误,本应操作链表节点的Next指针,实际操作的是头指针本身的地址空间。 - 头节点未初始化:
malloc分配头节点内存后,未初始化coeff、power、Next字段,全为随机野值。 - PrintList无有效遍历逻辑:仅打印头节点的野值后就退出,未遍历后续插入的有效节点,完全无法展示已插入的数据。
参考修正代码
#include <stdio.h> #include <stdlib.h> struct node { int coeff; int power; struct node* Next; }; void Insert(int X,int Y, struct node* head) { struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->coeff = X; temp->power = Y; temp->Next = head->Next; head->Next = temp; } void PrintList(struct node* head) { struct node* P = head->Next; while(P != NULL) { printf("%d %d ", P->coeff, P->power); P = P->Next; } printf("\n"); } int main() { struct node* head[3]; for(int q = 0; q < 3; q++) { head[q] = (struct node*)malloc(sizeof(struct node)); head[q]->Next = NULL; head[q]->coeff = 0; head[q]->power = 0; } Insert(1,2, head[0]); Insert(2,3, head[0]); Insert(1,2, head[1]); Insert(2,2, head[1]); for(int i = 0; i < 3; i++){ PrintList(head[i]); } // 释放已分配内存,避免泄漏 for(int q = 0; q < 3; q++) { struct node* p = head[q]; while(p) { struct node* tmp = p; p = p->Next; free(tmp); } } return 0; }
内容的提问来源于stack exchange,提问作者ameer anas
相关产品推荐
相关产品推荐

