我试图在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) { }};
我也无法弄清楚为什么当我尝试删除它时,它只会删除时间戳而不是时间戳和数量。所以当我运行我的交易存在功能时,它仍然说部分交易存在。
答案 0 :(得分:1)
当你delete
某事时,指针不会自动设置为nullptr
。这是程序员的责任。阅读Why doesn't delete set the pointer to NULL?
将指针设置为null时,它不会删除内存。如果你这样做,在你调用delete
之前,如果没有用引用它的另一个指针删除内存,你就会产生内存泄漏。
可以使用智能指针,这可以帮到你。