ttt23
ttt23

Reputation: 41

How to fix this error :pointer being freed was not allocated

I am new here and learning about topics of dynamic memory and linked list. And here is the problem that I have encountered.

void deletenode(Node*& head){
Node* temp = new Node;
temp = head; // I would like to create a new pointer to store the value of head node.
head=head->next; // and here I want to change the head node to the next one as I am going to delete it right after.

delete temp; // after I used the temp pointer to store the address of (the old) head, I would like to delete it.
}

But I still got the error message from it.

malloc: *** error for object: pointer being freed was not allocated
malloc: *** set a breakpoint in malloc_error_break to debug

In my prior knowledge of memory leak, if we do not delete the memory allocated by the new operator would cause memory leak as there will be so many garbage pointer. But why this problem still happened in my code as it seems like I have already deleted (or deallocated) the temp pointer. I really could not figure out what problem I have made as I have just learnt this topic and I may still have so many misconceptions about this topic.

UPDATED: Thanks for everyone's help. The problem has been solved. I just changed Node* temp = new Node; to Node* temp=head; And It works. Thank you so much for all of your advice!

Upvotes: 3

Views: 6350

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

Node* temp = new Node;

This creates a new object in dynamic scope, and sets temp to point to it.

At this point, you can go ahead and delete this object if you wish, and everything will work out at the end. But instead you do this:

temp = head;

This then immediately replaces the temp pointer, and it now points to some other mysterious object, that was passed into this function, that's referenced by this head pointer. If that object was also newed at some point, it can certainly be deleted, but even if that's the case this will result in a memory leak, since nothing else points to the original newed object, and it cannot be deleted.

 delete temp; 

Well, this is now pointing to whatever head was pointing. If head was pointing to something that was newed, it can be deleted here, otherwise this is undefined behavior, and a crash. And in all cases, the original new was leaked.

Upvotes: 2

Related Questions