title: double free or corruption (out) when trying to delete Nodes in a Binary tree
body: <p>I'm trying to make a recursive function to delete all nodes in my binary tree, where p->left and p->right are pointers to the next level in the tree. However it gives the following error message:</p>
  
  <p><strong>* Error in `./test.out': double free or corruption (out): 0x00007ffdf0cb3650 *</strong></p>
  
  <pre><code>struct Node {
      int key;
      double data;
      Node * right;
      Node * left;
  };
  
  void delete_tree(Node * &amp; p){
    if (p-&gt;left){
      delete_tree(p-&gt;left);
    }
    if (p-&gt;right){
      delete_tree(p-&gt;right);
    }
    delete p;
  };
  
  int main(){
    Node * currentNod = new Node;
    currentNod-&gt;key = 5;
    Node * newNode = new Node;
    newNode-&gt;key = 3;
    Node * newNode2 = new Node;
    newNode2-&gt;key = 6;
    delete_tree(currentNod);
    std::cout &lt;&lt; currentNod-&gt;key &lt;&lt; "\n";
    std::cout &lt;&lt; newNode-&gt;key &lt;&lt; "\n";
    std::cout &lt;&lt; currentNod-&gt;left-&gt;key &lt;&lt; "\n";
    return 0;
  </code></pre>
  
  <p>I've searched online and realize there can be problems when you have recursive functions with pointers, however delete_tree takes a reference, not a copy, so that problem should not apply here? I don't understand why it's not working :(</p>
  
  <p>EDIT: Changed the code, the problem was that when I was initializing currentNod I first created a Node object, and then i let currentNod be a pointer to that object. When i instead initialize it like this, it works. However, it does not print what I expect. This prints:</p>
  
  <p>0
  3
  Segmentation fault</p>
  
  <p>When i would expect it to give segmentation fault right away. Does anyone have an idea what could be the problem now? Thanks :) </p>