But the effect can be detrimental on a system (which includes most
desktop environments) where the allocator can detect duplicate frees.
For that reason, I never set a freed pointer to NULL.
Why not?
if (!ptr) ptr = make_object();
is the only choice you have to dedect an unset pointer, So
<type*> ptr = NULL; /* no object known yet */
.....
/* do something that will handle the object when it exists and ignore
it when not */
if (/* some condition that requires the object */) {
..... do something ....
}
.....
if (ptr) {
/* when we had a need to create the object do something with it */
}
.....
free(ptr);
ptr = NULL; /* we may come back to start later, so give the ptr a
clean state! again */
Without explicity clean up indeterminate pointers there is no chance
to avoid a crash by accessing it.
However a pointer ca be
- in use then it points to an existent object that can be
accessed
- is not in use then it is NULL, flagging that it is NOT in use
True, it makes no sense to set ptr to 0 when it goes thereafter out of
scope.
{
char *p = malloc(...);
if (!p) return return FAILED;
....
free p;
}
/* p does not exist anymore */
......
But
char *p = malloc(...);
/* do something with p */
free(p);
p = NULL; /* object pointed to by p is gone away */
......
if (!p) {
p = getit();
}
/* do something with p */
free(p);
return;
......
rules:
1. when a pointer is NULL then there is nothing assigned to,
so you can't use the pointer
2. When a pointer is NOT NULL then the object it points to exist
and you have access to it
3. free(NULL) is legal. So when your current scope knows of the
pointer and you has to give up the object it points to then
set the pointer to NULL after free() to flag that the pointer
is indeterminate now, because free() can't do that for you.
4. each malloc() needs a corresponding free()
or you'll end up with memory leaks
5. handle aliases carefully!
--
Tschau/Bye
Herbert
Visit
http://www.ecomstation.de the home of german eComStation
eComStation 1.2R Deutsch ist da!