googletest icon indicating copy to clipboard operation
googletest copied to clipboard

[Bug]: CRT library reports memory leak when using mock

Open MichielJazzy1 opened this issue 1 year ago • 0 comments
trafficstars

Describe the issue

The CRT library in windows reports a memory leak when using Nice/Naggy/ other Mock. A previous issue has been reported on this topic: https://github.com/google/googletest/issues/4109#issuecomment-1382251606. We cannot reliable detect other leaks anymore, because using mocks would always result in a leak detection by the CRT library.

The CRT is a industry standard on windows. Please reconsider writing the code in such a way that it doesn't lead to a memory leak (as detected by CRT). The definition of memory leak used is irrelevant. The industry standard tools (CRT, Valgrind) report it as an issue and it's hard to circumvent.

Steps to reproduce the problem

#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <crtdbg.h>

class MemoryLeakDetector
    : public testing::EmptyTestEventListener
{
public:
    virtual void OnTestStart(const testing::TestInfo&)
    {
        _CrtMemCheckpoint(&memState);
    }

    virtual void OnTestEnd(const testing::TestInfo& test_info)
    {
        if (test_info.result()->Passed())
        {
            _CrtMemState stateNow, stateDiff;
            _CrtMemCheckpoint(&stateNow);
            int diffResult = _CrtMemDifference(&stateDiff, &memState, &stateNow);
            if (diffResult)
            {
                _CrtDumpMemoryLeaks();
                FAIL() << "Memory leak of " << stateDiff.lSizes[1] << " byte(s) detected.";                
            }
        }
    }

private:
    _CrtMemState memState;
};

class MockClassToTest
{
};


TEST(MyTestClassToTest, test)
{
    testing::NaggyMock<MockClassToTest> niceClassToTest;
    //MockClassToTest t{};
}

int main(int argc, char** argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::UnitTest::GetInstance()->listeners().Append(
        new MemoryLeakDetector());
    return RUN_ALL_TESTS();
}

What version of GoogleTest are you using?

1.12

What operating system and version are you using?

Windows 10

What compiler and version are you using?

MSVC 17.10, compiler v144

What build system are you using?

MSVC 17.10

Additional context

No response

MichielJazzy1 avatar Sep 11 '24 09:09 MichielJazzy1