gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:51:58 24 4
gpt4 key购买 nike

对于我的作业,我需要创建从双端队列添加(追加)和删除(服务)节点的方法。然而,当尝试服务最后一个节点时,我遇到了内存泄漏的问题,因为我不知道如何检索系统不再使用的节点。这是该方法的代码。

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”库

最佳答案

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

例如,您可以使用智能指针,例如std::unique_ptr而不是打电话 new DequeNode调用std::make_unique<DequeNode>() 。然后,编译器将指出您的代码需要调整的位置,因为您将限制自己,以便每个 DequeNode 同时仅由一个 unique_ptr 拥有。基于您的serveAtRear的示例pop函数(其中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)
}

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

关于c++ - 使用链表从双端队列中删除最后一个节点时避免内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61911806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com