Saturday, May 22, 2010

Question about linked lists in C?

When you free the last element of a dynamically allocated linked list ( something like "free(cur);" ), does the next pointer of the previous link node then become a NULL pointer? Or does it still point to the location of the freed memory? That is, do I have to explicitly set that next pointer (now the tail of the list) to NULL?

Question about linked lists in C?
You have to explicitly set the pointer to null.





Indeed you have to manage all the pointer for manipulating lists in C. I usually dont call free directly but do it in a Destroy function. If you have a list of 'CAT' objects for example your function would be like this -





void CatDestroy (CAT *cat)


{


if (cat-%26gt;next) cat-%26gt;next-%26gt;previous = cat-%26gt;previous;


if (cat-%26gt;previous) cat-%26gt;previous-%26gt;next = cat-%26gt;next;


free (cat);


}





This gives you a degree of extra flexibility. For example you can change how a CAT is allocated so that its dosent use free() and malloc(). You could decrement the number of cats variable. You could link the CAT into a list of unused CATs rather than freeing it. You could update a pointer to the tail of the list.


No comments:

Post a Comment