> I've written some code to make a hash data structure and associated
funtions (insert, delete, search). In the delete function, I want to free()
the key and the associated value. But since I want to be able to use this
code, I can't discount the chance that the key or the value are static
values on the stack. If this is the case, then free() will (obviously) fail.
free() is not guaranteed to fail obviously. free() may fail in a
subtle manner that is maximally embarassing or expensive (e.g. it
only fails in front of the customer or the chairman of the board.
Or it only fails when it is in production and then it shuts down
the power grid in several states or scatters pieces of spacecraft
over hundreds of miles).
On Solaris <sys/ucontext.h> has a function stack_inbounds that will return
a non-zero value if the address passed to it is in the heap, but this
function isn't portable -- only Solaris implements it.
Functions like this can get, um, "interesting" when you try to use
threads. Of course, those aren't standard either.
So the really short version of the question is: How can I test to see if a
pointer points to malloc() assigned space (on the heap) or is a static value
defined in the data stack?
You invoke the wrath of undefined behavior.
if ((void)fflush(++(void)main++)) {
/* variable was allocated from the toilet */
} else {
/* variable was allocated from the garbage dump */
}
is one way to make it fail at compile time so you'll know right
away that it won't work. I'm not aware of a system-specific way
to do this other than the one you mentioned for Solaris, and
a system on which malloc() always fails.
Oh, yes, there's more choices than this. The pointer can point to
malloc() assigned space, it could point to an automatic variable
(what stack?), it could point to static data in the program, or it
could point to static data in a shared library (which often blows
to bits system-specific assumptions about the addresses of "the
beginning and end of the data segment"). ANSI C does not provide
for shared libraries but it doesn't prohibit them either.
Or you make sure that all of the values are, in fact, allocated
with malloc() by making copies yourself. This, obviously, involves
a change in strategy for the caller of your function for freeing
allocated memory once.
Gordon L. Burditt