title: how to free memory for doubly linked list program in c
body: <p>Past few days I'm working on my c\c++ skills. I was going through my Data structure book and then I thought why not implement doubly linked list program. I wrote the program; surprisingly it work fine too, but , I'm not sure whether I've written it correctly. I'm not able to figure it out how to free the memory I've allocated. Please help me with this guys. </p>
  
  <p>Also if any of you can explain me this "while(linkNode!=0)", i'll be really thankfull.</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;malloc.h&gt;
  
  struct node
  {
      int x;
      struct node * next;
      struct node * prev;
  };
  
  struct head
  {
      unsigned int count;
      struct node * hd;
      struct node * tl;
  
  };
  
  
  void main()
  {
      int i =0;
  
      struct node * linkNode;
      struct head *hdd;
  
      hdd = (head *)malloc(sizeof(head));
  
      linkNode = (node *) malloc(sizeof(node));
      hdd-&gt;count = 1;
      hdd-&gt;hd = linkNode;
      linkNode-&gt;prev = 0;
      linkNode-&gt;next = 0;
      linkNode-&gt;x = 0;
  
  
      for(;i&lt;10;i++)
      {
          linkNode-&gt;next = (node *) malloc(sizeof(node));
          linkNode-&gt;next-&gt;prev = linkNode;
          linkNode = linkNode-&gt;next;
          linkNode-&gt;next = 0;
          linkNode-&gt;x = i;
          hdd-&gt;count+=1;
          hdd-&gt;tl = linkNode;
  
      }
  
      linkNode = hdd-&gt;hd;
      printf("priniting in next direction\n");
      while(linkNode!=0)
      {
          printf("%d\n",linkNode-&gt;x);
          linkNode = linkNode-&gt;next;
      }
  
  
      linkNode = hdd-&gt;tl;
      printf("priniting in prev direction\n");
      while(linkNode!=0)
      {
          printf("%d\n",linkNode-&gt;x);
          linkNode = linkNode-&gt;prev;
      }
  
      linkNode = hdd-&gt;hd;
      while(linkNode!=0)
      {
          free(linkNode-&gt;prev);
          linkNode = linkNode-&gt;next;
  
      }
  
      free(hdd);
  
  
  }
  </code></pre>