Search code examples
c++windowsunit-testingheap-profiling

How can a regression test prove whether VirtualAlloc was called?


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.)


Solution

  • 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.