There's "*str=NULL;" missing after "free(*str);" - in case free() will be used, and return value of function ignored...
Printable View
That is the typical method but depends on what you're doing. It is not required and I see your point, but if you're going to be using pointer allocations this way you might want to make a wrapper for free() that sets it for you:
Code:void * safe_free(void * ptr)
{
if(ptr)
free(ptr);
return NULL;
}
var = safe_free(var);
It is safe to free a null pointer, so one could write:
But then since this requires one to remember to assign the return value of safe_free() back to the pointer, I see no benefit over just writing:Code:void * safe_free(void * ptr)
{
free(ptr);
return NULL;
}
Code:free(var);
var = NULL;
I would prefer something like this:
--Code:void safe_free(void **ptr)
{
if (ptr) // Check for stupid programmer errors
{
free(*ptr);
*ptr = NULL;
}
}
// And to complete it...
#define free(x) safe_free(&x)
Mats
Yes all very good points of preference... and back to what was being said:
"... so do something... or not"
or better yet, you could just:Rather than having an IF, in that case.Code:assert(ptr);