How can a regression test prove whether VirtualAlloc was called?

147 Views Asked by At

I'm writing a regression test for a (Win7) C++ routine that is being optimized, which formerly freed and re-allocated a lot of giant buffers: memory churn. I would like to prove that during the test, the program doesn't allocate any large memory regions (say 16M or larger) but instead efficiently re-uses its memory that was allocated at initialization time. It comes down to that the test should fail if VirtualAlloc has been called to get some large region (say 16M).

Is there an elegant way to count stats on calls to Windows VirtualAlloc? This would become part of the permanent automatic regression test suite, so using an external tool or modifying the downstream code is not feasible.

Checking the total memory committed is not a good fit, because I want to assert that the routine is no longer churning (freeing and re-allocating buffers.)

2

There are 2 best solutions below

1
On BEST ANSWER

Hooking

Detours can hook arbitrary method calls, but

  • it is free for non-commercial use only
  • it is perhaps overkill for a unit test

Rohitab and Easyhook seem to provide something similar.

Alternatives

If your process is 32 bit, you could allocate 4080 MB (more or less) in advance and more calls to VirtualAlloc would fail. This would not cover cases where you allocate/deallocate 16 MB multiple times. If you make these 4080 MB reserved, this will even be fast, since no real memory is needed.

0
On

Dependency Injection.

Instead of having the code under test call the native memory allocators, you pass in a pointer to an allocator object that the code can use instead. For production code, this allocator object simply calls the native memory allocation functions. For the test, you pass in an allocator that checks and/or logs the sizes.