Re: free()



[some re-flow]
Chris Dollin said:
Richard Heathfield wrote:
Chris Dollin said:
Beej wrote:
void delete_goat(GOAT *g) { free(g); g = NULL; }

[...] where the assignment of NULL is completely pointless.

...but then it's a pointless function anyway.

It frees the store its argument points to and names what's
going on, so the /function/ isn't pointless.

free(whatever_you_would_have_passed_to_delete_goat); would do the same
trick, though - it frees the memory and (if the pointer is well-named)
documents what's going on as well, to anyone who knows what free() is
for - and if they don't know, why are we letting them touch production
code?

I write destructors like this:

void goat_delete(GOAT **g)
{
if(g != NULL)
{
if(*g != NULL)
{
GOAT *p = *g; /* purely for notational convenience */
horn_delete(&p->horn);
trollgun_delete(&p->trollgun);
leg_delete(&p->leg);
free(p);

*g = NULL; /* *not* a pointless assignment */
}
}
}

Interesting. I'm trying to articulate why I find that overkill.
I /think/ it's that where I free something, either the place
I'm freeing it from is about to evaporate (as in your horn,
leg, and trollgun), so the assignment doesn't help,

It might not only be goats that use trollguns, and anyway there may be
other circumstances where you need to destroy a trollgun other than the
one where you are destroying - sorry! deleting - a goat.

[...] Probably because
we're writing different kinds of code. With a shared goal:
"don't let invalid pointers screw you up - get rid of them PDQ".

Yeah. The thing is, different people think in different ways. There's
more than one way to do it, as the Perl people are so fond of reminding
us - and what seems natural and elegant to one person may well seem
kludge-ugly to another. There are lots of right ways. (And vastly more
wrong ways...)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
.