S
Skarmander
avasilev said:Hi all,
my question is:
if i allocate some memory with malloc() and later free it (using
free()), is there a possibility that a consequent malloc() will
allocate memort at the same starting address and will return the same
pointer as the previous malloc(). I would like to have confirmation on
whether this is practically a concern when pointers are used to
uniquely identify data structure instances - like in this example:
int isInstanceValid(myStrict* inst)
{
int i;
for (i=0; i<instCount; ++i)
if (instances == inst)
return 1;
return 0;
}
In this example, if an instance is freed, and a pointer to it becomes
non-valid, and later a new structure is allocated in the list, the
function will return that the pointer is valid, although it is actually
not the instance that was originally referred.
Aside from everything else that's already been said: don't do this.
There is no way to detect whether a pointer is valid (in any sense of the
word) in portable C, and in most cases it's not feasible to do it in
unportable C either.
If you concerned about not deallocating things before their time is up, use
a garbage collector, like http://www.hpl.hp.com/personal/Hans_Boehm/gc/.
If you're concerned about sloppy programmers (possibly including yourself as
a culprit), then audit your code more closely, using tools like valgrind
(http://valgrind.org/) and Electric Fence
(http://perens.com/FreeSoftware/ElectricFence/).
If you want a unique identifier for an object, come up with one yourself,
and don't make it depend (exclusively) on its address. This is what the
concept of a handle is all about, although handles are subject to mistakes
like these too. You may be able to devise a handle allocation scheme that
will maximimze the time before reuse and hence increase the chance of
detecting an invalid handle.
The best even most external tools can do is increase the likelihood of
detecting an allocation bug. They cannot convince you there aren't any.
S.