Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!cmcl2!stealth.acf.nyu.edu!brnstnd From: brnstnd@stealth.acf.nyu.edu Newsgroups: comp.lang.c Subject: Re: free (NULL) Message-ID: <1074:May3000:24:1990@stealth.acf.nyu.edu> Date: 30 May 90 00:24:19 GMT References: <1771@mindlink.UUCP> <2574@skye.ed.ac.uk> <3078@goanna.cs.rmit.oz.au> Reply-To: brnstnd@stealth.acf.nyu.edu (Dan Bernstein) Organization: IR Lines: 22 In article <3078@goanna.cs.rmit.oz.au> ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes: [ on the general problem of how to tell if an object is no longer ] [ being pointed to ] > Can anyone suggest a better way of tackling this problem in portable C? Your second solution does the job most of the time: keep a count next to each pointer. With a disciplined style such as is enforced by, say, C++ or a good macro set, you'll never forget to deal with the count. However, you do run into a problem with pointer loops: some number of structures, each containing a pointer to the next one in a circle, and none of which you actually need. There are solutions to this fundamental problem, for which I refer you to Knuth's discussion of Lists. Most of the time you don't need general List structures, and there's some way to modify your design so that it's always clear when you can free a pointer. One common technique is to do as little allocation as possible in subroutines; whenever you do allocate something, you must deallocate it in the same block. This fails only when a parent can't predict how much memory a child will need, which is rare in practice. ---Dan