Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!sdd.hp.com!spool.mu.edu!uwm.edu!ux1.cso.uiuc.edu!phil From: phil@ux1.cso.uiuc.edu (Phil Howard KA9WGN) Newsgroups: comp.lang.c Subject: Re: Deleting linked lists. Keywords: C, C++. Message-ID: <1991Mar27.025307.20808@ux1.cso.uiuc.edu> Date: 27 Mar 91 02:53:07 GMT Article-I.D.: ux1.1991Mar27.025307.20808 References: <2636@borg.cs.unc.edu> Distribution: na Organization: University of Illinois at Urbana Lines: 35 warner@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@ux1.cso.uiuc.edu \ \ Lietuva laisva -- Brivu Latviju -- Eesti vabaks / \***************************************************************************/