Reputation: 356
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
Upvotes: 0
Views: 151
Reputation: 1444
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.
}
Upvotes: 0