Check if a pointer points to allocated memory on the heap

A proof it probably cannot be usefully done:

char * p1 = malloc(1);
free( p1 );
char * p2 = malloc(1);   // probably allocates same block as first malloc

Now both p1 and p2 point at same memory on heap, but only p2 is valid.


There's no standard way to do this, but various malloc debugging tools may have a way of doing it. For example, if you use valgrind, you can use VALGRIND_CHECK_MEM_IS_ADDRESSABLE to check this and related things


You can do this yourself, if performance is not a real issue for your application:

Define MyMalloc(...) and MyFree(...) in which, along with calling malloc/free, you update a (ordered)list of pairs {address -- the result of malloc, blockSize -- the amt of memory requested }. Then when you need to check a pointer p, you look for a pair satisfying: address <= p <= address + blockSize.

Other conditions could/should be checked, if you want to actually use that pointer, this will only tell if an address is in use or not.


Mudflap (for gcc) seems very sweet. You have to compile your soft with but it will check any wrong pointer access (heap/stack/static). It is designed to work for production code with slowdown estimated between x1.5 to x5. You can also disable check at read access for speedup.
User check can be performed using

void __mf_check (void *ptr, __mf_size_t sz, int type, const char *location)

Calling this function results to: nothing, fork to gdb, segv or abort depending on environment parameters.