Deleting linked lists.

Dave Gillett dgil at pa.reuter.COM
Tue Apr 2 08:58:53 AEST 1991


In <2636 at borg.cs.unc.edu> warner at weiss.cs.unc.edu (Byron Warner) writes:

>struct list *head; /* top of list */
>struct list *ptr = head;
>while (ptr){
>	free(ptr);
>	ptr = ptr->next;
>}

    Even if the value of ptr is not changed by free(), you have absolutely no
guarantee that the value at ptr->next is still valid.  Some implementations of
free() can corrupt data in the freed block; even if this is not true, in some
environments that block might get allocated to somebody else before your
dereference of ptr.  You need another pointer:

struct list *head, *p1;
struct list *ptr = head;
while (ptr){
       p1 = ptr->next;
       free (ptr);
       ptr = p1;
}

                                                 Dave



More information about the Comp.lang.c mailing list