Can we unit test memory allocation?
You cannot write a unit test for this function, because you cannot allocate memory on the heap without a system call. Hence, this is an integration test, as you are unable of isolating the unit under test from the operating system.
I would create a new, small executable that calls allocation_routine
for n
bytes. Depending on what allocation_routine
is supposed to return, you can assert that it's non-nullptr
. Then, write n
bytes into this region of memory. Compile and link it using the address sanitizer (available with both gcc
and clang
), then try to integrate it into the test runner of your application (ctest
etc.).
You might also want to restrict the available heap via the POSIX setrlimit to verify the behvaior when the allocation fails.