title: Seg-Fault at BST remove() Function
body: <p>Basically the program consists of a BST class that points to the first node of a Binary Tree, and the Nodes are also their own class.</p>
  
  <p>The BST calls this member function:</p>
  
  <pre><code>void remove(const T&amp; x)
  {
      removeNode(m_root, x);
      return;
  }
  </code></pre>
  
  <p>And this is the recursive part of the remove node, which runs to completion:</p>
  
  <pre><code>template &lt;typename T&gt;
  void removeNode(TreeNode&lt;T&gt;* &amp;p, const T&amp; x)
  {
      if(p == NULL)
          return;
  
      if(x &lt; p -&gt; m_data)
          removeNode(p -&gt; m_left, x);
      else if(x &gt; p -&gt; m_data)
          removeNode(p -&gt; m_right, x);
  
      else
      {
          TreeNode&lt;T&gt;* tmp = new TreeNode&lt;T&gt;;
  
          if(p -&gt; m_left == NULL)
          {
              tmp = p -&gt; m_right;
              delete p;
              p = tmp;
          }
          else if(p -&gt; m_right == NULL)
          {
              tmp = p -&gt; m_left;
              delete p;
              p = tmp;
          }
          else
          {
              tmp = p -&gt; m_right;
              TreeNode&lt;T&gt;* tmp2 = new TreeNode&lt;T&gt;;
  
              while(tmp -&gt; m_left != NULL)
              {
                  tmp2 = tmp;
                  tmp = tmp -&gt; m_left;
              }
  
              p -&gt; m_data = tmp -&gt; m_data;
  
              if(tmp2 != NULL)
                  removeNode(tmp2 -&gt; m_left, tmp -&gt; m_left -&gt; m_data);
              else
                  removeNode(p -&gt; m_right, p -&gt; m_right -&gt; m_data);
          }
      }
  
      return;
  }
  </code></pre>
  
  <p>I am seg-faulting right as the remove() function returns, and I would like to know why?</p>