Is there any way to identify if a buffer was allocated by 'malloc'? like a function with the following signature:
bool is_malloced(void *buf);
Does such a mechanism exist in posix?
Is there any way to identify if a buffer was allocated by 'malloc'? like a function with the following signature:
bool is_malloced(void *buf);
Does such a mechanism exist in posix?
mmm if you are a serious person, you could actually do:
Hash *hsh; /* global hash already initialized. */
void *custom_malloc(size_t size)
{
void *ptr;
ptr = malloc(size);
hash_add(hsh, ptr);
return ptr;
}
/* tester */
_Bool malloced(void *ptr)
{
if(hash_retrieve(hsh, ptr))
return TRUE;
return FALSE;
}
of course doing such thing is madness, but indeed you can.
One simple way to emulate such a functinality would be to wrap malloc()
in a custom function which:
Given a pointer one can check if it is malloc
'ed by looking for the magic number.
Of course, it is not perfect:
free()
call can help. XOR-ing it with the pointer, etc. can also make it more reliable. Still, it's a heuristic.With all the drawbacks, it's still a useful technique, I've used it a few times when debugging some memory corruption in embedded systems.
If we are about to replace malloc()
with some wrapper, we could as well build a linked list of allocated blocks. Much more reliable, but also more complex.