Deleting linked lists.
Henry Spencer
henry at zoo.toronto.edu
Thu Mar 28 04:15:26 AEST 1991
In article <2636 at borg.cs.unc.edu> warner at weiss.cs.unc.edu (Byron Warner) writes:
>I was wondering, is it safe to unallocate a singly linked list like this:
>while (ptr){
> free(ptr);
> ptr = ptr->next;
>}
No. This code is unsafe for three reasons. The first is that the free()
may destroy the contents of the memory ptr points at, so ptr->next may
no longer have its old value. (Some existing implementations leave the
memory alone, and some programmers have carelessly come to rely on this,
but that is unwise.) The second, more subtle, is that even the attempt
to reference ptr->next may cause disaster, because the memory might not
even be there any more -- it might have been given back to the operating
system, so any reference to it will cause a trap. Third and subtlest,
it is not entirely clear that you can even examine the value of the pointer
safely when it no longer points to anything, although it would take a very
strange machine to get you in trouble on this one.
>I am not sure if I can assume that
>the value of ptr will not be corrupted
>after it is freed.
The free() can't alter the value of ptr itself, but as mentioned above,
there is some possibility that it will be unsafe to use that value, and
considerable possibility that it won't do what you want.
The right way to do this is to tuck the value of ptr->next away in a
temporary variable before doing the free().
--
"[Some people] positively *wish* to | Henry Spencer @ U of Toronto Zoology
believe ill of the modern world."-R.Peto| henry at zoo.toronto.edu utzoo!henry
More information about the Comp.lang.c
mailing list