Re: free()



Chris Dollin said:

Beej wrote:

On Feb 13, 1:38 pm, Richard Heathfield <r...@xxxxxxxxxxxxxxx> wrote:
Short of writing an entire pointer management subsystem, there isn't
much you can do with a pointer to check it for validity, but you
*can* test it against NULL. If you know it's NULL, you know it's
invalid. If it isn't NULL, you can't be sure either way. So setting
it to NULL when it would otherwise be indeterminate is a Good Thing,
because it increases the amount of information available to you at a
trivial cost.

At last... this thread is finally starting to boil down to "NULL
makes a great sentinel value." ;)

-Beej

void delete_goat(GOAT *g)
{
free(g);
g = NULL;
}

This being a place where the assignment of NULL is completely
pointless.

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

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 */
}
}
}

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



Relevant Pages

  • Re: free()
    ... much you can do with a pointer to check it for validity, ... a great sentinel value." ... void delete_goat ...
    (comp.lang.c)
  • Re: confusion: casting function pointers
    ... pointer from the 'actual/other modules' that takes arguments of type ... list to types of void *). ... int main{ ... without a prototype, a number of special "promotion" rules take ...
    (comp.lang.c)
  • Re: [RFC] timers, pointers to functions and type safety
    ... * they have callback of type void ... callback is called by the code that even in theory has no ... cast to unsigned long and cast back in the callback. ... number - not a pointer cast to unsigned long, not an index in array, etc. ...
    (Linux-Kernel)
  • Re: Can I Trust Pointer Arithmetic In Re-Allocated Memory?
    ... You can't do pointer arithmetic on a void* value. ... qsort behaves in a manner consistent with its specification. ... actually works as advertised...but doesn't mean that the cast is ...
    (comp.lang.c)
  • Re: The void** pointer breaking symmetry?
    ... void** is a generic pointer type that can be implicitly converted ... because dereferencing the void ** variable once gives ...
    (comp.lang.c)