title: How does malloc works in this case?
body: <p>Here is code of my program I use <code>gcc -Wall -ansi -g</code></p>
  
  <p>This program makes binary tree and prints it in order. But there is problem for me.</p>
  
  <p>I can't make my root  = NULL and have to alloc memory that should in my opinion be marked on NULL.</p>
  
  <p>There is another problem. How does it work if there is no NULL but allocated memory? Does malloc allocate memory of <code>(*root) -&gt; right_child</code> or <code>left_child</code> on NULL. I totally don't get it. There is Segmentation fault if I don't allocate memory like this. Any help and critic will be welcome.</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  /*struct for node it has pointers and value*/
  struct node {
      struct node *left_child ;
      struct node *right_child;
      int val;
  };
  
  /*Prints error message out of memory*/
  
  void outOfMemoryError(void){
      fprintf (stderr,"out of memory error :(\n");
      fflush(stderr); 
      exit (123);
  }
  
  /*print tree inorder*/
  void printTreeInOrder (struct node **rootNode){
      if ( (*rootNode) == NULL)
      {   
  #ifdef DEBUG
          printf("## my node is null");
  #endif
  
          return;
      } 
      if ( (*rootNode)-&gt;left_child !=NULL){
          printTreeInOrder( (*rootNode) -&gt;left_child);
      }
  
      printf ("%d ",(*rootNode) -&gt;val);
      if ((*rootNode)-&gt;right_child !=NULL){
          printTreeInOrder((*rootNode)-&gt;right_child);
      }
  }
  
  /*add node uses recursion*/
  void addNode (struct node **root, int value ){
      if ( (*root) == NULL) {
  #ifdef DEBUG
          printf("## my root is null\n");
          fflush (stdout);
  #endif
          (*root) = malloc (sizeof (struct node));
  
          if (root == NULL)
              outOfMemoryError();
          (*root) -&gt;val = value;    
          /* I don't know why I have to malloc this memory instead using NULL*/
          (*root) -&gt;left_child = malloc (sizeof (struct node));
          (*root) -&gt;right_child = malloc (sizeof (struct node));
      }
      else if ((*root) -&gt;val &gt; value){
          addNode ((*root)-&gt;right_child,value);
      }
      else  
          addNode ((*root)-&gt;left_child,value);
  
  }
  
  int main(void)
  {   
      /*input vars*/
      char string [80];
      int temp = 0;
  
      /*root of the whole tree*/
      struct node *root = malloc (sizeof (struct node));
  
      printf ("i will add to binnary tree as long as int is bigger than 0\n");
      while (1) {
          fgets (string,sizeof(string),stdin);
          sscanf(string,"%d",&amp;temp);
          if (temp &lt;= 0)
              break;
          addNode(root,temp);
      }
      printf("Printing tree Inorder\n");
      printTreeInOrder(root); 
      return 0;
  }
  </code></pre>