I’m working with linked lists for my first time and have to create a function that can insert a node at the end of a doubly linked list. So far I have
void LinkedList::insertAtTail(const value_type& entry) {
Node *newNode = new Node(entry, NULL, tail);
tail->next = newNode;
tail = newNode;
++node_count;
}
The Node class accepts a value to be stored, a value for the next pointer to point to, and a value for the previous pointer in that order. Whenever I try to insert a node here, I get an error saying there was an unhandled exception and there was an access violation in writing to location 0x00000008.
I’m not entirely sure what’s going wrong here but I assume it has something to do with dereferencing a null pointer based on the error message. I would really appreciate some help with solving this problem.
EDIT:
I should have clarified early, tail is a pointer that points to the last node in the list. Tail->next accesses the next variable of that last node which, before the function runs, points to NULL but after it executes should point to the new node created.
Where does
tailpoint to initially? If it’s NULL then you’ll dereference a null pointer when trying to insert the first element.Does it help if you test
tailbefore dereferencing it?If
tailis null andoffsetof(Node, next)is 8 that would explain the access violation, becausetail->nextwould be at the address 0x00000000 + 8 which is 0x00000008, so assigning totail->nextwould try to write to memory at that address, which is exactly the error you’re seeing.