Deleting linked lists.
Phil Howard KA9WGN
phil at ux1.cso.uiuc.edu
Wed Mar 27 12:53:07 AEST 1991
warner at weiss.cs.unc.edu (Byron Warner) writes:
>I was wondering, is it safe to unallocate a singly linked list like this:
>
>struct list *head; /* top of list */
>struct list *ptr = head;
>while (ptr){
> free(ptr);
> ptr = ptr->next;
>}
>
>I am not sure if I can assume that
>the value of ptr will not be corrupted
>after it is freed.
The value of "ptr" won't be corrupted, but that value is useless after you
have done the "free(ptr)". What can be corrupted is "ptr->next" since that
memory is now deallocated. It might appear to work on your system, but it
cannot be trusted and is certainly wrong.
Try this:
struct list *head; /* top of list */
struct list *ptr = head;
while (ptr){
register struct list *temp_ptr;
temp_ptr = ptr->next;
free(ptr);
ptr = temp_ptr;
}
--
/***************************************************************************\
/ Phil Howard -- KA9WGN -- phil at ux1.cso.uiuc.edu \
\ Lietuva laisva -- Brivu Latviju -- Eesti vabaks /
\***************************************************************************/
More information about the Comp.lang.c
mailing list