Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!zaphod.mps.ohio-state.edu!rpi!sci.ccny.cuny.edu!phri!cmcl2!stealth.acf.nyu.edu!brnstnd From: brnstnd@stealth.acf.nyu.edu Newsgroups: comp.lang.c Subject: Re: free (NULL) Message-ID: <17486:Jun611:18:1690@stealth.acf.nyu.edu> Date: 6 Jun 90 11:18:16 GMT References: <1771@mindlink.UUCP> <2574@skye.ed.ac.uk> <1074:May3000:24:1990@stealth.acf.nyu.edu> <3102@goanna.cs.rmit.oz.au> <3466:May3022:56:1890@stealth> <9YT3MP@xds13> <270:Jun113:33:1590@stealth> Reply-To: brnstnd@stealth.acf.nyu.edu (Dan Bernstein) Organization: IR Lines: 44 In article peter@ficc.ferranti.com (Peter da Silva) writes: > In article <270:Jun113:33:1590@stealth.acf.nyu.edu> brnstnd@stealth.acf.nyu.edu (Dan Bernstein) writes: [ and we argue: ] > > > > Namely: Whatever you allocate inside a routine, you also deallocate > > > > inside that routine. If your memory needs are variable, provide enough > > > > information to your callers that they can allocate for you. (This is > > > > called ``passing the buck.'') > > > I disagree with this entirely. > > So what are you disagreeing with? > The paragraph quoted above. > Consider a routine "readline(fp)". this (hypothetical) routine reads in > a line of text and allocates and returns a pointer to it. It appears that > you do not believe that this is a reasonable thing to do. C'mon, Peter, this is the third time you've just left out the third part of my paragraph. It's perfectly fine to keep allocated memory around between calls, and even pass up a pointer to that memory, *provided* that the pointer isn't *defined* by your interface as a pointer to *allocated* memory. In other words, you must provide an unreadline() to free the memory. > Consider the commonly implemented routine "strdup" that allocates a copy > of a string and returns a pointer to the copy. This is a mistake, because the pointer is *defined* by the interface as a pointer to *allocated* memory. Either the parent should malloc() and strcpy(), or strdup() should also have an unstrdup() to free the memory. > > I don't think I'm totally off base, > > because Boyd Roberts made the same three-way classification in a > > simultaneous article. > He didn't make any hard-and-fast rule about never returning a malloc-ed > chunk of memory to ones parent. Just make sure that the interface is > properly documented and consistent. Again, it doesn't matter whether internally you malloced the memory or used a static area. Just never return a chunk of memory that's *defined* to be malloc()ed. (This is what he said.) To put it differently: Never, ever, ever pass internally malloc()ed memory up to your parent (this is what I said)---but, as always in C, feel free to apply the as-if rule. ---Dan