title: binary tree segment fail in c
body: <p>Hi guys I am implementing a binary search tree in c. It seems insertion to tree works fine. But when searching, it gives a segmentation fail. Please review my code and give a reason for this issue and how to overcome it. Thanks in Advance.</p>
  
  <p>following is the code....</p>
  
  <pre><code>struct node{
  int data;
  struct node *leftChild;
  struct node *rightChild;
  </code></pre>
  
  <p>};</p>
  
  <pre><code>struct node *root=NULL;
  void insert(int data){
  
  struct node *current=NULL;
  
  if(root==NULL){
      root=(struct node*)malloc(sizeof(struct node));
      root-&gt;data=data;
      printf("Root data:%d\n",root-&gt;data);
  
  }else{
      current=root;
      //Searching the posistion
      while(true){
          if((current-&gt;data)&lt;data){
              current=current-&gt;rightChild;
  
          }else{
              current=current-&gt;leftChild;
          }
          if(current==NULL){
              break;
          }
      }
      struct node *tempData;
      tempData=(struct node*)malloc(sizeof(struct node));
      tempData-&gt;data=data;
      tempData-&gt;leftChild=NULL;
      tempData-&gt;rightChild=NULL;
      current=tempData;
      printf("Current data:%d\n",current-&gt;data);
  
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>struct node* search(int data){
  sstruct node *current=root;
  if(current==NULL){
      return;
  }else{
  
      while(current-&gt;data!=data){
          printf("%d",current-&gt;data);
  
          if((current-&gt;data)&lt;data){
              current=current-&gt;rightChild;
  
          }else{
              current=current-&gt;leftChild;
  
          }
          //printf("Hello world!:%d\n",current-&gt;data);
  
          if(current==NULL){
              printf("%d",current-&gt;data);
              return NULL;
          }
  
      }
      return current;
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>And My main() method is....</p>
  
  <pre><code>insert(10);
  insert(20);
  insert(4);
  insert(16);
  search(20);
  </code></pre>