You need to enable JavaScript to run this app. 遍历双向链表时结构异常变化触发display函数段错误问题排查
优惠活动
大模型
产品
解决方案
定价
更多

遍历双向链表时结构异常变化触发display函数段错误问题排查

错误原因

核心错误出在insertAfter函数的指针赋值逻辑:

  • newNode本身就是指向你malloc出来的节点的指针变量,代码里写的tmp->next = &newNode、nextNode->prev = &newNode是完全错误的,这里取的是栈上存储newNode这个指针变量本身的内存地址,不是你申请的堆上节点的地址。
  • 这个栈地址在insertAfter函数执行结束后就会被释放回收,后续其他函数运行时会覆写这块内存,就会出现你看到的节点data莫名变成\000、链表结构随机损坏的问题,最终遍历的时候访问非法内存触发段错误。
  • 另外原有逻辑还漏了索引等于链表最后一个节点位置的场景处理,此时tmp->next是NULL,原有代码不会执行插入操作。

修复方法

把insertAfter函数的错误部分修改如下即可:

void insertAfter(char c, int index)
{
    struct node *tmp = head;
    int currIndex = 0;
    // 遍历到对应索引位置,支持到最后一个节点
    while (tmp != NULL && currIndex < index)
    {
        currIndex++;
        tmp = tmp->next;
    }
    // 先判断索引合法
    if (tmp != NULL && currIndex == index)
    {
        struct node *newNode = malloc(sizeof(struct node));
        newNode->data = c;
        newNode->prev = tmp;
        newNode->next = tmp->next;
        if (tmp->next != NULL)
        {
            // 直接赋值newNode,不要取地址
            tmp->next->prev = newNode;
        }
        // 直接赋值newNode,不要取地址
        tmp->next = newNode;
    }
}

另外最小可复现代码里的printf(xyz-1\n");漏了开头的双引号,补上为printf("xyz-1\n");即可正常编译。

内容的提问来源于stack exchange,提问作者Juan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 17:12:02