C ++ delete not working?

I have a problem with deletion and destructor (I'm sure I'm making a stupid mistake here, but I still can not figure it out).

When I go to the destructor and try to call delete on the pointer, the message "Cannot access memory at address with some address" appears in the message.

Relevant Code:

/*
 * Removes the front item of the linked list and returns the value stored
 * in that node.
 *
 * TODO - Throws an exception if the list is empty
 */
std::string LinkedList::RemoveFront()
{
    LinkedListNode *n = pHead->GetNext(); // the node we are removing
    std::string rtnData = n->GetData(); // the data to return

    // un-hook the node from the linked list
    pHead->SetNext(n->GetNext());
    n->GetNext()->SetPrev(pHead);

    // delete the node
    delete n;
    n=0;

    size--;
    return rtnData;
}

and

/*
 * Destructor for a linked node.
 *
 * Deletes all the dynamically allocated memory, and sets those pointers to 0.
 */
LinkedListNode::~LinkedListNode()
{
    delete pNext; // This is where the error pops up
    delete pPrev;
    pNext=0;
    pPrev=0;
}
+3
source share
3 answers

It seems that you are removing the next and previous list nodes from the destructor. Which, if pNextand pPrev LinkedListNode*, means that you recursively delete the entire list: - (

Try the following:

std::string LinkedList::RemoveFront()
{
    LinkedListNode *n = pHead->GetNext(); // the node we are removing
    std::string rtnData = n->GetData(); // the data to return

    // un-hook the node from the linked list
    pHead->SetNext(n->GetNext());
    n->GetNext()->SetPrev(pHead);

    n->SetNext(0);
    n->SetPrev(0);
    // delete the node
    delete n;
    n=0;

    size--;
    return rtnData;
}

LinkedListNode::~LinkedListNode()
{
}

( reset prev next 0, node. , node , . , .)

+5

, LinkedListNode , , node, - , pNext pPrev NULL node.

LinkedListNode , : delete pNext, delete pPrev ( , ).

+1

In fact, you should not bother with neighbors in node. It is for the list class to properly connect them. In the destructor, you can set them to null, but if you have not dynamically allocated something else, you do not need to calldelete

0
source

Source: https://habr.com/ru/post/1741609/


All Articles