I would like to be able to detect if my function (or any other function it calls) will end up calling some specific functions (for instance, malloc and free) in my unit tests: some small portions of my software have hard-real-time requirements, and I'd like to ensure that no ones adds something that would trigger an allocation by accident in these functions (and have my CI pipeline check it automatically).
I know that I can just put a breakpoint on gdb, but ideally I'd like to do something like :
void my_unit_test() {
my_object obj; // perform some initialization that will allocate
START_CHECKING_FUNCTION(malloc); // also, operator new or std::allocate would be nice
obj.perform_realtime_stuff();
STOP_CHECKING_FUNCTION(malloc);
}
ideally, the test would fail in a not-too-dirty way (eg not std::abort) if at some point malloc is called between the two checks.
Ideally, this would run on any system, but I can live with something that only does it on linux for now. Is this possible in some way ? Maybe through a LD_PRELOAD hack that would replace malloc, but I'd rather not have to do this for all the functions I'm interested in.
If you're using libraries which invoke malloc, then you might want to take a look at the Joint Strike Fighter C++ Coding Standards. It's a coding style aimed towards mission critical software. One suggestion would be to write your own allocator(s). Another suggestion is to use something like
jemallocwhich has statistics, but is much more unpredictable since it is geared towards performance.What you want is a mocking library with spy capabilities. How this works for each framework is going to vary, but here is an example using Google:
WARNING: Code hasn't been touched by compiler hands. But you get the idea.