我试图在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
最佳答案
当您对delete
进行编码时,指针不会自动设置为nullptr
。这样做是程序员的责任。在Why doesn't delete set the pointer to NULL?中阅读更多内容
将指针设置为null时,它不会删除内存。如果这样做,则在调用delete
之前,如果不使用引用它的另一个指针删除内存,则会创建内存泄漏。
可以使用智能指针,为您解决问题。