free (NULL)

Martin Weitzel martin at mwtech.UUCP
Thu Jun 7 04:33:08 AEST 1990


In article <17486:Jun611:18:1690 at stealth.acf.nyu.edu> brnstnd at stealth.acf.nyu.edu (Dan Bernstein) writes:
>In article <WUU3BX6 at xds13.ferranti.com> peter at ficc.ferranti.com (Peter da Silva) writes:
[part of discussion deleted]
>
>> 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.

Mistake of whom? The designer of the library? Though I surely appreciate
information hiding and the clean constructor/destructor approach of C++,
concerning some relative `low level' operations I can see a trade-off:

Either you are willing to `unobscure' things a little and loose the
potential to change your implementation (this is what the designer
of "strdup" did)
			or

you may get lots of "unallocating" request, most of which boil down to:

	#define unstrdup	free
	#define unreadline	free
	....

Note that I left out macro parameters here, so that even the adress
of some `un'-allocating operation may be passed around without writing
functions. Of course you can write `real' functions:

	void unstrdup(char *s) { free(s); }
	void unreadline(char *s) { free(s); }
	....

which has the disadvantage of beeing slower and the advantage that
the programmer will not get confused by some source level debuggers.

Note that I'll not recommend the one over the other! It's a trade-off
and it's not my task to judge the designer of "strdup". One tiny little
bit of criticism is that "strdup" should be included in the "malloc/
calloc/free" man page ... (if I were to write the manuals :-)), but
that only emphasizes Peters point a little: Make sure that it is
documented *and* try to stomp the reader of the documentation onto it.
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.lang.c mailing list