C++ Exception thrown: read access violation. this was nullptr

The LinkedList destructor has a couple of problems. First, it’s pointless to set m_size to 0 and a to NULL since they will both go away at the end of the destructor. More important, the code will attempt to dereference a null pointer when the list is empty:

Node* a = m_front; // okay, gets that head pointer
Node* b = a->getNext(); // bang!!

Here’s a cleaner way to write it:

Node* a = m_front;
while (a != NULL) {
    Node *temp = a->getNext();
    delete a;
    a = temp;
}

Leave a Comment