title: LinkedList - How to free the memory allocated using malloc
body: <p>I have a very simple C code for constructing a Singly Linked list as below, in which I allocate memory for each node dynamically using malloc. At the end of code, I want to free the memory for each node allocated, was wondering how to go about it - If I start from head node first and free it, the pointers to the subsequent nodes are lost and memory leak happens. </p>
  
  <p>Other way is start from head node and keep storing the node pointer in a separate array of pointers or something, traverse the list till the tail pointer while storing the node pointers, and once reach the tail node, store that also to the other array of pointers and start freeing from that array index backwards until the head node is free'ed. </p>
  
  <p>Is that the only way to achieve what I am trying to do? </p>
  
  <p>In case if I dont want to use second buffer, how do I go about it.</p>
  
  <pre><code>#include "stdio.h"
  #include "stdlib.h"
  
  struct lnk_lst 
  {
     int val;
     struct lnk_lst * next;
  };
  
  typedef struct lnk_lst item;
  
  
  main()
  {
     item * curr, * head;
     int i,desired_value;
  
     head = NULL;
  
     for(i=1;i&lt;=10;i++) 
     {
        curr = (item *)malloc(sizeof(item));
        curr-&gt;val = i;
        curr-&gt;next  = head;
        head = curr;
     }
  
     curr = head;
  
  
     while(curr) {
        printf("%d\n", curr-&gt;val);
        curr = curr-&gt;next;
     }
  
    //How to free the memory for the nodes in this list?
     for(i=1;i&lt;=10;i++)
     {
         free()//?? What logic here
     }
  
  
  }
  </code></pre>