I’m getting a memory leak reported for this incomplete test case. If I pass “nameNameNameNam” instead then there is no report of a leak.
TEST_F (TestDoesExist, namePassedToCInterface)
{
Accessor accessor(_cInterface, _handle);
accessor.doesExist(std::string("nameNameNameName"));
}
The code under test looks like this:
virtual bool doesExist(const std::string& name)
{
bool result;
_cInterface.exists(_txHandle, name.c_str(), &result);
return result;
}
The call to the C interface is mocked as follows:
class MockDoesExist
{
public:
MockDoesExist() {
handle=Handle();
name = "";
result = true;
}
static void func(Handle _handle, const char* _name, bool* _result) {
// in values
handle = _handle;
name = _name;
// out values
*_result = result;
}
// in values
static Handle handle;
static std::string name;
// out values
static bool result;
};
Handle MockDoesExist::handle;
std::string MockDoesExist::name;
bool MockDoesExist::result;
I’m comiling with VS 2010 express.
I have:
_CrtMemCheckpoint( &memAtStart );
before the testcase execution and:
_CrtMemDifference( &memDiff, &memAtStart, &memAtEnd)
after.
What am I doing wrong?
Nothing. The
_CrtMemDifferenceis called after the test case, but before the static members ofMockDoesExistget destroyed (they get destroyed just before program termination). During your test case,MockDoesExist::namegets assigned your long string. In MSVC’s standard library there is a optimization for short strings, meaning each std::string has an internal 16 byte char array where shorter strings may be stored. Only for longer strings it has to allocate memory from the free store. That memory will be released in the string’s destructor, in this case whenMockDoesExist::namegets destroyed, i.e. after_CrtMemDifferencegets called.