使用链接列表从双端队列中删除最后一个节点时避免内存泄漏

问题描述 投票:0回答:1

对于我的作业,我需要制作一些方法来添加(附加)和从Deque中删除(提供)节点。但是,当尝试为最后一个节点提供服务时,由于我不知道如何检索系统不再使用的节点,因此我遇到了内存泄漏的问题。这是该方法的代码。

void Deque::serveAtRear(int &x)
{
  if(empty())
  {
      cout << "Fila Vazia" << endl;
      exit(0);
  }
  else
  {
      DequePointer q;         //Pointer before p
      q = head;               //q starts at the deque's head
      p = head->nextNode;     //Pointer for the next node

      if(q->nextNode==NULL)   //If there's only one node
      {
         x = q->entry;        //x will receive the value of the removed node to print it afterward
         head = tail = NULL;
         delete p;            //I don't know if I'm using the "delete" right
      }
      else
      {
         while(p->nextNode != NULL)
         {
             p = p->nextNode;
             q = q->nextNode;
             if(p->nextNode==NULL)
             {
                 q->nextNode=NULL;
             }
         }
         x = p->entry;
         delete p->nextNode;
     }
     delete q->nextNode;
  }

}

要添加节点,我有此方法:

void Deque::appendAtFront(int x)
{

  if(full())
  {
     cout << "FULL" << endl;
     exit(0);
  }
  else
  {
     p = new DequeNode;
     p->entry=x;
     if(p == NULL)
     {
         cout << "Can't insert" << endl;
         exit(0);
     }
     else if(empty())
     {
         head = tail = p;
         p->nextNode=NULL;
     }
     else
     {
         p->nextNode=head;
         head = p;
     }
  }
}

而且我也不能使用“ deque”歌词库

c++ memory-leaks linked-list deque
1个回答
0
投票

如何避免泄漏的通用答案是:避免手动分配内存。

例如,您可以使用智能指针,例如std::unique_ptr,而不是调用new DequeNode,请调用std::make_unique<DequeNode>()。然后,编译器将指出需要修改代码的位置,因为这将限制您自己,以便每个DequeNode仅由one unique_ptr拥有。基于您的serveAtRear的示例弹出功能(其中headDequeNode.next是uniuque_ptrs):

if (!head)
{
    return;
}
DequeNode* q;          //Pointer before p 
DequeNode* p;          //will be tail eventually 
q = head.get();        //q starts at the deque's head 
p = q->next.get();     //Pointer for the next node 

if(!p)   //If there's only one node 
{       
        x = q->entry; //x will receive the value of the removed node to print it afterward 
        head.reset(); // hear we release DequeNode pointed by head
}       
else    
{       
        while(p->next) 
        {       
                q = p;  
                p = q->next.get(); 
        }       
        x = p->entry; 
        q->next.reset(); // here we release tail (i.e. p)
}       

当然也需要采用push的实现:)。

© www.soinside.com 2019 - 2024. All rights reserved.