title: Segfault-Iterative insert in BST
body: <p>I'm trying to write a code to insert a new element in the BST iteratively. When I try to execute the code, I get a segfault. Can someone look over the code and help me correct it? </p>
  
  <pre><code>bool insert2(int item)
  {
      BstNode *parent;
      BstNode *root=new BstNode;
      cout&lt;&lt;root-&gt;data;
      cout&lt;&lt;"\n";
      BstNode *ptr;
      int ctr=0;
  
      //cout&lt;&lt;root-&gt;data;
      if (root==NULL)
      {
          BstNode *temp=new BstNode;
          temp-&gt;data=item;
          temp-&gt;left=NULL;
          temp-&gt;right=NULL;
          root=temp;
          //cout&lt;&lt;root-&gt;data;
          return true;
  
      } 
      else
      {
          ptr=root;
          while (ptr!=NULL)
          {
              ctr=ctr+1;
              cout&lt;&lt;ctr;
              if (ptr-&gt;data==item)
              {
                  cout&lt;&lt;ptr-&gt;data;
                  return false;
              }
  
              if (item &lt; ptr-&gt;data)
              {
                  parent=ptr;
                  ptr=ptr-&gt;left;
  
              } 
              else
              {
                  parent=ptr;
                  ptr=ptr-&gt;right;
              }
  
          }
          BstNode *add=new BstNode;
          add-&gt;data = item;
          add-&gt;left= NULL;
          add-&gt;right= NULL;
          return true;
      }
  }
  </code></pre>
  
  <p>on editing out the root-> data part, the code would go into the first if block and return true, which makes me guess that my problem lies somewhere in the deceleration. </p>