PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Checking if a pointer is already allocated or not?

I am trying to implement a function that will check to see if a pointer is valid (allocated) within the default process heap.

I would like to stay away from replacing the malloc(), calloc() and free() functions with my own.

Is there a posibility this could be done in C?
Not sure if this will do what you need, but check the Win32 API for IsValidReadPtr() and IsValidWritePtr(). I am not sure they exist under WCE.
I'm not aware of any such C APIs, but as mentioned there are likely other APIs that provide that functionality.
I tried using IsBadWritePtr... and it doesn't work, it returns 0 if the memory block is assigned and 0 if it's freed also.

What would then be the best method if I create my own methods for malloc, calloc, free and strdup without losing speed?

I was thinking about assigning a 4 bytes value at the beginning of the block and then return the pointer as location + 4 in malloc and calloc. In free, I could reset the pointer - 4 (4 bytes value) to zero let's say and if I need to check to see if the pointer exists, I could check if pointer - 4 is zero or not?

Would this work even though the location as been freed?
a disadvantage of this method is that your pointers would no longer be optimally aligned (32-byte aligned) taking into account it was ever that way.

i suggest to use a hash table to store all your pointer addresses...

bye,
Daniel
kornalius wrote:I tried using IsBadWritePtr... and it doesn't work, it returns 0 if the memory block is assigned and 0 if it's freed also.

What would then be the best method if I create my own methods for malloc, calloc, free and strdup without losing speed?

I was thinking about assigning a 4 bytes value at the beginning of the block and then return the pointer as location + 4 in malloc and calloc. In free, I could reset the pointer - 4 (4 bytes value) to zero let's say and if I need to check to see if the pointer exists, I could check if pointer - 4 is zero or not?

Would this work even though the location as been freed?


I can tell you that not only have I used this before, but some very large video game companies have used this and shipped countless games with it. As far as 32 byte alignment goes, that should be a non-issue as your extra 4 byte padding would only be added in debug mode. Release mode would be raw allocs/frees.

That 4 byte header can be a pointer to an allocation table in debug mode to tell you not only if the memory has been freed, but where the memory was allocated, how much was allocated, what its allocation number was, etc. You get some really nice heapdumps with all that info, which is useful for systems with crappy memory managers.