c++ - GMock leaks memory on 'Uninteresting mock function calls' since update - Stack Overflow

admin2025-04-18  6

Since updating GTest framework from 1.8.x to 1.12.x, there have been a few tests that report memory leaks at the end of the test.

I've stripped out all the complexity of our setups to the example below and tested it on the old framework and the new. This sample does not show memory leaks in the old, it now does. It seems to be triggered by a function call made on the mock for which there isn't an explicit EXPECT.

Uncommenting the expectation line makes the memory leak go away.

The mock in our original code was a static shared_ptr, but making it a class member, or stack variable in the test, don't fix the issue.

The offending allocation appears to be the instantiation of an unordered_map inside 'UninterestingCallReactionMap()' in gmock-spec-builders

using namespace testing;

class IFoo
{
public:

    IFoo() = default;
    virtual ~IFoo() = default;

    virtual bool closeLink(void) = 0;
};

class MockFoo : public IFoo
{
public:
    MOCK_METHOD0(closeLink, bool());
};

class MemLeakReproTest : public Test
{
};

TEST_F(MemLeakReproTest, TestStuff)
{
    MockFoo mockFoo;

    //EXPECT_CALL(mockFoo, closeLink()).Times(1).WillOnce(Return(true));
    mockFoo.closeLink();
}

Edit: added in response to the question about how we are detecting the leaks.

This is in the main.cpp of the test project (running on Windows). Is our setup in main correct?

{
 // Enable leak checking on exit
 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
 // Write CRT warnings to stderr
 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);

 wchar_t filename[MAX_PATH] = {};
 wcscpy_s(filename, *wargv);
 wcscat_s(filename, L".memleaks");

 hLogFile = CreateFile(filename, GENERIC_WRITE,
     FILE_SHARE_READ, NULL, CREATE_ALWAYS,
     FILE_ATTRIBUTE_NORMAL, NULL);

 _CrtSetReportHook(reportHook);

 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);

 testing::InitGoogleTest(&argc, argv);
 int result = RUN_ALL_TESTS();

 LocalFree(wargv);

 return result;
}
转载请注明原文地址:http://www.anycun.com/QandA/1744970079a90198.html