C语言链表重复数字计数函数出现段错误,求排查错误原因
排查C语言无序链表重复计数函数的段错误问题
我编写了一个C语言函数countRedun,参数为存储整数链表起始地址的指针,功能是返回链表中数字重复出现的总次数。例如链表元素为7777时返回3(数字7额外出现3次),元素为8233982时也返回3。
链表结构定义:
struct digit { int num; struct digit *next; };
函数代码如下:
int countRedun(struct digit * start) { struct digit * front = start; struct digit * back = start->next; int i, a[10]; for (i = 0; i < 10; i++) { a[i] = 0; } while (front != NULL) { while (back != NULL) { if (front->num == back->num) { a[front->num] ++; } back = back->next; } front = front->next; while (a[front->num] > 0) { front = front->next; } if (front != NULL) { back = front->next; } } int s = 0; for (i = 0; i < 10; i++) { s += a[i]; } return s; }
我的实现思路:用两个指针front和back,front从链表头部开始,back从第二个节点开始,对比后续节点与front指向节点的数字;当back遍历到链表末尾后,front仅移动到未统计过数字的节点,否则继续后移。但运行该函数时出现段错误,需要排查错误所在。
错误点分析及修复方案
- 空链表未处理:函数开头直接访问
start->next,如果传入空链表(start为NULL),会直接触发段错误。需先判断空链表,直接返回0。 - front后移后未判空就访问成员:
front = front->next;之后,front可能变为NULL,此时while (a[front->num] > 0)会访问空指针的num成员,导致段错误。必须先判断front不为NULL,再执行这个循环。 - 链表末尾全为已统计节点时的空指针访问:如果
front后移到NULL,后续操作依然会出错,需在循环中持续判断front的有效性。
修复后的代码
int countRedun(struct digit * start) { // 处理空链表 if (start == NULL) { return 0; } struct digit * front = start; struct digit * back; int a[10] = {0}; // 直接初始化数组为0 while (front != NULL) { // 如果当前数字已经统计过,直接跳过 if (a[front->num] != 0) { front = front->next; continue; } back = front->next; while (back != NULL) { if (front->num == back->num) { a[front->num]++; } back = back->next; } front = front->next; } int s = 0; for (int i = 0; i < 10; i++) { s += a[i]; } return s; }
内容的提问来源于stack exchange,提问作者konxanth
相关产品推荐
相关产品推荐

