free (NULL)

brnstnd at stealth.acf.nyu.edu brnstnd at stealth.acf.nyu.edu
Wed Jun 6 21:18:16 AEST 1990


In article <WUU3BX6 at xds13.ferranti.com> peter at ficc.ferranti.com (Peter da Silva) writes:
> In article <270:Jun113:33:1590 at stealth.acf.nyu.edu> brnstnd at 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



More information about the Comp.lang.c mailing list