简体   繁体   中英

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!

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 new ed at some point, it can certainly be delete d, but even if that's the case this will result in a memory leak, since nothing else points to the original new ed 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 new ed, it can be delete d here, otherwise this is undefined behavior, and a crash. And in all cases, the original new was leaked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM