Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!saxony!dgil From: dgil@pa.reuter.COM (Dave Gillett) Newsgroups: comp.lang.c Subject: Re: Deleting linked lists. Keywords: C, C++. Message-ID: <846@saxony.pa.reuter.COM> Date: 1 Apr 91 22:58:53 GMT References: <2636@borg.cs.unc.edu> Distribution: na Organization: Reuter:file Inc (A Reuter Company) Palo Alto, CA Lines: 24 In <2636@borg.cs.unc.edu> warner@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