Access violation exception after deleting the head node of a doubly linked list in C++

0

This is my delete function

void deleteNode(Node** head, Node* deletingNode) {
    if (head == NULL || deletingNode == NULL)
        return;
    if (*head == deletingNode) {
        *head = deletingNode->next;
        displayNode(*head); //This is to check if the head has changed. And it has.
    }
    if (deletingNode->next != NULL)
        deletingNode->next->prev = deletingNode->prev;
    if (deletingNode->prev != NULL)
        deletingNode->prev->next = deletingNode->next;
    delete(deletingNode);
    return;
}

After I delete the head node and try do anything with the linked list, for example, display the whole linked list like so

void displayNode(Node* node) {
    cout << left << setw(4) << node->employee.empID
        << left << setw(20) << node->employee.empName
        << left << setw(8) << node->employee.empSalary
        << left << setw(25) << node->employee.empAddress
        << left << setw(15) << node->employee.empPhone
        << left << setw(2) << node->employee.depNo
        << left << setw(28) << node->employee.depName
        << left << setw(4) << node->employee.performance
        << '\n';
}
void displayAllNodes(Node* node) {
    displayColumnNames();
    while (node != NULL) {
        displayNode(node);
        node = node->next;
    }
}

An exception is thrown at the second line of the above block

Exception thrown at 0x78DBE26E (ucrtbased.dll) in Project.exe: 0xC0000005: Access violation reading location 0xDDDDDDDD. occurred

This ONLY happens when I delete the head node. Works just fine if I delete any other node.

So far I have tried making the double pointer in the deleteNode function into a single pointer but that didn't make a difference.

The whole code: https://codeshare.io/5oV8Jr

c++
linked-list
access-violation
head
asked on Stack Overflow Jan 1, 2020 by Mismaah • edited Jan 1, 2020 by Mismaah

1 Answer

0

Update: Following the fix from comments section(thanks to drescherjm and Igor Tandetnik), here's another bug I found and a quick fix to that.

I believe there's an issue is in this part of code:

if (*head == deletingNode) {
  *head = deletingNode->next;
  displayNode(*head); //This is to check if the head has changed. And it has.
}

What if you have just 1 node in the linked list and you call deleteNode(). Now head and deletingNode points to the same node and *head = deletingNode->next; sets the head to NULL after which you're calling displayNode(*head); which will throw an error.

Quick fix:

if (*head == deletingNode) {
  *head = deletingNode->next;
  if(*head != NULL)
    displayNode(*head); //This is to check if the head has changed. And it has.
}
answered on Stack Overflow Jan 1, 2020 by Ajay Dabas • edited Jan 1, 2020 by Ajay Dabas

User contributions licensed under CC BY-SA 3.0