In <65************ **************@ posting.google. com>
an***********@c a.com (Andrew) writes:
Is there anyway to test if a pointer points to allocated memory or
not?
For example if I have a pointer such as char *p is there a standard
way to test whether an assignment such as the following has been
applied?
p = (char *) malloc(sizeof(c har) * n);
If the pointer has not yet been initialised or if it points to memory
that has been already freed, you're not even allowed to evaluate it in
a portable C program.
In a well designed program, you don't need such a check: you should
know whether it is initialised or not. The alternative takes a lot of
programming discipline: initialise each pointer with NULL at the point of
definition and reset it to NULL as soon as the object it used to point to
no longer exists (or is about to disappear). You may find the
following macro useful for this purpose:
#define FREE(p) (free(p), p = NULL)
but it is far from solving the problem, because there may be other
pointers pointing into the block being free'd. But malloc and friends
are not the full story. Consider:
char *global;
void foo(void)
{
char buff[100];
global = buff;
...
}
You need a "global = NULL;" before returning from foo(), because the life
of buff ends at that point.
So, if you're *extremely* careful, you can always use p != NULL to tell
whether p is pointing to some object or not (bugs caused by omitting to
reset a pointer can be very difficult to track). IMHO, it's much easier
to avoid the need of such checks in the first place.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email:
Da*****@ifh.de