14
votes

I have to test a library that provides its own memory allocation routine:

void* allocation_routine(size_t size) throw();

Documentation states that this function allocates at least size bytes of memory (it's allowed to allocate more). By the way the function uses posix_memalign internally, but the implementation may change.

I'm wondering if it's possible to write a unit test for that kind of functions? How can we test whether the required amount of memory was allocated?

UPDATE:

If we can't write a unit test then what is the closest solution?

2
You will want to choose either C or C++ tags. The languages are quite different in exception handling, see How to throw an exception in C? or throw expression - cppreference.com - David C. Rankin
I suggest mocking the standard memory allocation functions to check if they are called (and with which size). Most implementations allow this relatively easily. For specific help, you'll need to provide which specific implementation you're working with, and (as David C. Rankin asked) specify which language you're using (C and C++ are different languages). - Sander De Dycker
For example in gcc (C), you'd use memory allocation hooks. - Sander De Dycker
@DavidC.Rankin This routine is from the .cpp file. But the code is very C-style. I would suppose that C-solution is more appropriate there. - embedc

2 Answers

16
votes

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.

0
votes

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.