Checking if a pointer is allocated memory or not

You cannot check, except some implementation specific hacks.

Pointers have no information with them other than where they point. The best you can do is say “I know how this particular compiler version allocates memory, so I’ll dereference memory, move the pointer back 4 bytes, check the size, makes sure it matches…” and so on. You cannot do it in a standard fashion, since memory allocation is implementation defined. Not to mention they might have not dynamically allocated it at all.

You just have to assume your client knows how to program in C. The only un-solution I can think of would be to allocate the memory yourself and return it, but that’s hardly a small change. (It’s a larger design change.)

Leave a Comment