Can we unit test memory allocation? Can we unit test memory allocation? linux linux

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.


It's not unit test, but you can use Valgrind to get different information about memory.

  • memory leaks (which are not free)
  • memory issues

It's mainly used for debugging, but it will warns you if something is not allocated well.