Reputation: 10699
So I'm recreating a LinkedList
in C++ and I am trying to change the pointer to the last Node
in my list. Here is my overloaded +=
operator where all the magic and errors happen. I have two different ways of changing the pointer, but both throw Unhandled exception at 0x00ee42f3 in Lab3.exe: 0xC0000005: Access violation writing location 0xccccccec.
. What is going on and how can I fix it?
void MyLinkedList::operator+=(const std::string& s)
{
allocator<Node> a;
Node* n = a.allocate(1);
a.construct(n, s);
if (first == NULL)
first = n;
else
{
(*last).next = n; // crashes here
(*last).SetNext(n); //also will crash here, if the previous statement is removed
last = n;
}
}
To further clarify, it will go through and set the first Node
, exit the method, and the next time it is called will run and enter the else
statement. At this point there is a second Node
, it is allocated in memory and instantiated. What I am trying to do is set the Node* next
pointer in the first Node
to this new Node
, but it throws the exception. Sorry for being very vague initially.
Upvotes: 1
Views: 2532
Reputation: 35440
Your operator += has a lot of issues.
1) The operator+= should return a reference to this, not void. Otherwise a+=b makes no sense.
MyLinkedList& MyLinkedList::operator+=(const std::string& s)
{
//...
return *this;
}
2) Second, your last pointer may not have been initialized if the list is empty.
3) Style issue -- why are you doing this:
(*last).next = n;
when you should just do this:
last->next = n;
?
Upvotes: 1
Reputation: 438
We do not know the allocate
and SetNext
specific realization.
If they are no problem, please look here:
if (first == NULL)
{
first = n;
last = first; // You should assign last with the head node pointer.
}
...
Maybe it help.
Upvotes: 2