title: How to fix this error :pointer being freed was not allocated
body: <p>I am new here and learning about topics of dynamic memory and linked list. And here is the problem that I have encountered.</p>
  <pre><code>void deletenode(Node*&amp; head){
  Node* temp = new Node;
  temp = head; // I would like to create a new pointer to store the value of head node.
  head=head-&gt;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.
  }
  </code></pre>
  <p>But I still got the error message from it.</p>
  <pre><code>malloc: *** error for object: pointer being freed was not allocated
  malloc: *** set a breakpoint in malloc_error_break to debug
  </code></pre>
  <p>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 <code>temp</code>  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.</p>
  <p>UPDATED:
  Thanks for everyone's help. The problem has been solved. I just changed <code>Node* temp = new Node;</code> to <code>Node* temp=head;</code> And It works. Thank you so much for all of your advice!</p>