You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

链表addNode与deleteByPhrase函数触发段错误如何排查修复

代码问题分析

1. addNode函数问题

  • 插入pos=0位置的逻辑错误:当链表原本存在节点时,直接将头指针指向新节点且新节点next设为nullptr,会直接丢弃原有整个链表,不仅造成内存泄漏,还会导致后续访问原有节点时触发非法访问。

2. deleteByPhrase函数问题(段错误核心诱因)

  • 删除非头节点逻辑错误:当前代码删除非头节点时直接将previous->next设为nullptr,会直接丢弃当前节点之后的所有链表节点,后续访问这些已丢失的节点时会触发非法访问。正确逻辑应该是将previous->next指向当前节点的下一个节点current->next。
  • 删除节点后指针迭代逻辑错误:节点被判定为需要删除时,完成删除操作后仍然将previous赋值为已删除的current节点,后续如果访问previous的成员会触发野指针访问,直接导致段错误。
  • 缺少被删除节点的内存释放逻辑,存在内存泄漏。

修复代码

修复后的addNode函数

void addNode(node* &h, int pos, string phrase)
{
    if(pos == 0)
    {
      node* newHead = new node;
      newHead->phrase = phrase;
      newHead->id = pos;
      nodeCount++;
      newHead->next = h; // 原有链表接在新头节点后
      h = newHead;
    }
    else if(pos <= nodeCount)
    {
      node* y;
      node* g = h;
      int count = 0;
      while(count != pos && g!=nullptr)
      {
        y = g;
        g = g->next;
        count++;
      }
      node *n = new node;
      n->id = pos;
      nodeCount++;
      n->phrase = phrase;
      n->next = g;
      y->next = n;
      // 若业务要求节点id连续,可在此处添加逻辑将后续节点id统一+1
    }   
}

修复后的deleteByPhrase函数

void deleteByPhrase(node* &h, string deletionPhrase)
{
   struct node* current = h;
   struct node* previous = nullptr;
   while(current != nullptr)
   {
    if(current->phrase.find(deletionPhrase) != string::npos)
    {
      node* temp = current;
      if(current == h) {
        h = h->next;
        current = h; // 头节点删除后直接跳转到新头节点
      }else{
        previous->next = current->next; // 前后节点拼接
        current = current->next;
      }
      delete temp; // 释放被删除节点内存
      nodeCount--;
    }
    else
    {
      // 无需删除时才移动前序指针
      previous = current;
      current = current->next;
    }
   }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:57:01