gpt4 book ai didi

c++ - 内存泄漏删除节点 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:07:51 27 4
gpt4 key购买 nike

我试图在 C++ 中删除链表中的一个节点,但在删除事务后它一直说 _pending_tx 不是 nullptr。 valgrind 还说我有内存泄漏,我无法弄清楚

bool BankData::void_transaction(const size_t& customer_id, const size_t& timestamp) { 

bool var8 = false;

if (transaction_exists(customer_id, timestamp) == true)
{
int blah3 = customerVector.size();
for (int i = 0; i < blah3; i++)
{
if (customerVector.at(i)._customer_id == customer_id)
{
if (customerVector.at(i)._pending_txs != nullptr)
{
CSE250::dTransactionNode *temp = customerVector.at(i)._pending_txs;
while (temp->_tx._timestamp != timestamp)
{
temp = temp->_next;
if ((temp->_next == nullptr) && (temp->_tx._timestamp != timestamp))
{
var8 = false;
}
}
if (temp->_tx._timestamp == timestamp)
{
if ((temp->_prev == nullptr) && (temp->_next == nullptr)) //head and only node
{
delete customerVector.at(i)._pending_txs;
customerVector.at(i)._pending_txs = nullptr; //after i delete the head and only node i reset it to a nullptr
var8 = true;
}
else if ((temp->_prev == nullptr) && (temp->_next != nullptr)) //head
{
temp = customerVector.at(i)._pending_txs->_next;
delete customerVector.at(i)._pending_txs;
customerVector.at(i)._pending_txs = temp;
customerVector.at(i)._pending_txs->_prev = nullptr;
var8 = true;
}
else if ((temp->_prev != nullptr) && (temp->_next == nullptr)) //tail
{
temp = customerVector.at(i)._pending_txs->_prev;
delete customerVector.at(i)._pending_txs;
customerVector.at(i)._pending_txs = temp;
customerVector.at(i)._pending_txs->_next = nullptr;
var8 = true;
}
else //middle node
{
temp = customerVector.at(i)._pending_txs->_next;
customerVector.at(i)._pending_txs->_next->_prev = customerVector.at(i)._pending_txs->_prev;
delete customerVector.at(i)._pending_txs;
customerVector.at(i)._pending_txs = temp;
//temp->_prev->_next = temp->_next;
//temp->_next->_prev = temp->_prev;
//temp = nullptr;
//delete temp;
var8 = true;
}
}
}
}
}
}
return var8;

这是我要删除的节点结构:

namespace CSE250 {
struct dTransactionNode;}

struct CSE250::dTransactionNode {
Transaction _tx;

dTransactionNode* _prev;

dTransactionNode* _next;

dTransactionNode(size_t time, double amount) : _tx(time, amount), _prev(nullptr), _next(nullptr) { }};

我也不明白为什么当我尝试删除它时,它只会删除时间戳而不是时间戳和金额。所以当我运行我的交易存在功能时,它仍然说交易的一部分存在。

That's the valgrind message

And those are the error messages I get that say its not pointing to a nullptr after the transaction has been voided even thoguh i set it manually to a null ptr

最佳答案

当您删除 某些内容时,指针不会自动设置为nullptr。程序员有责任这样做。在 Why doesn't delete set the pointer to NULL? 中阅读更多内容

当您将指针设置为空时,它不会删除内存。如果这样做,在调用 delete 之前,如果您不使用引用它的另一个指针删除内存,就会造成内存泄漏。

可以使用智能指针,它可以为您解决问题。

关于c++ - 内存泄漏删除节点 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46866262/

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