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!