Newsgroups: comp.lang.c Path: utzoo!henry From: henry@zoo.toronto.edu (Henry Spencer) Subject: Re: Deleting linked lists. Message-ID: <1991Mar27.181526.7554@zoo.toronto.edu> Date: Wed, 27 Mar 1991 18:15:26 GMT References: <2636@borg.cs.unc.edu> Organization: U of Toronto Zoology In article <2636@borg.cs.unc.edu> warner@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@zoo.toronto.edu utzoo!henry