cmemoryfree

2 ways of freeing memory of a simple linked list in C?


I created a linked list in C called lon with the help of following functions:

struct ilist_node {
   struct ilist_node * rest;
   int first;
};

typedef struct ilist_node *ilist;


ilist icons(int in, ilist il) {
   ilist r = malloc(sizeof(struct ilist_node));
   r->first = in;
   r->rest = il;
}

Then I incremented the list with icons to create a list of numbers.

After that, I tried to print each element in the list and free the memory used by the list by

while (lon!= NULL) {
      ilist tmp = lon->rest;
      printf(" %d\n",lon->first);
      free(lon);
      lon = tmp;
   }

I can understand why this function above works. (I googled how to free memory and this one seems to be the popular answer). But out of curiosity, I tried another one:

   ilist tmp = lon;
   while (lon != NUll) {
      printf(" %d\n",lon->first);
      lon = lon->rest;
   }

   idelete(tmp);

and it also works. So I'm a little confused. If the last one works, then why do I need to go through the list and free every node?


Solution

  • Until I can see the source code for idelete, I can't comment. At the risk of being a PITA I don't think anyone can accurately comment.

    We need the source for idelete.

    idelete may be

    void idelete(ilist il) {
       while (il!= NULL) {
          ilist tmp = il->rest;
          free(il);
          il = tmp;
       }
    }
    

    which would work fine.