One easy way to emulate such a function is to wrap malloc() in a user-defined function that:
- allocates a buffer which is for example 4 bytes larger
- stores some magic number (32 bits) at the beginning of the selected block
- increments a pointer by 4 bytes before returning it to the caller
Given the pointer, you can check if there is a malloc 'ed by looking for a magic number.
Of course, this is not ideal:
- the magic number may be there by accident. This can help set it to null in a wrapped
free() call. XOR-ing with a pointer, etc. It can also make it more reliable. However, this is a heuristic. - on memory-protected architectures, you can cause a page error when checking for a pointer that was not malloc'ed.
With all the flaws, this is still a useful method, I used it several times when debugging memory corruption on embedded systems.
If we are going to replace malloc() with some shell, we could also build a linked list of allocated blocks. It is much more reliable, but also more difficult.
source share