Note that while you can't unit test a malloc replacement directly you can if there is any level of indirection. Otherwise as @lubgr has stated this is an integration test.
Indirection can help on both sides. If you have a malloc wrapper that counts memory for example:
extern "C" void* malloc(const size_t size) __THROW
{
return getAllocator().malloc(size);
}
struct Allocator
{
using MallocFunc = std::function<void*(size_t)>;
unsigned long numAllocs = 0;
size_t totalMemAllocated = 0;
MallocFunc = __libc_malloc;
void* malloc(const size_t size)
{
++numAllocs;
totalMemAllocated += size;
return __libc_malloc(size);
}
}
You could instead set MallocFunc
to point to your own mock version of malloc()
instead of __libc_malloc
to test the accounting mechanism works properly.
Likewise you can test the allocation routine itself if you provide interposed or mock versions of the system calls it uses in the unit test code.
If using gcc you might consider using symbol wrapping or the LD_PRELOAD mechanism for this.
Remember that integration tests are important as well. The assumptions you make during unit testing may not hold.