IMallocSpy trouble
Hi!
I'm having some problems tracking down memory allocation errors using
IMallocSpy. The following is a scenario which actually led me to use
IMallocSpy:
1. At some point in the program a previously allocated BSTR is
overwritten with some new value, tough it was not freed explicitly by
the program.
2. By the time the original BSTR is being deallocated, it is corrupted
and the program crashes.
This suggests that at some point the SysFreeString is called twice on
the same BSTR which leads to the described behavior. So, I've used
IMallocSpy to track the error down. Unfortunately, it showed that no
extra IMalloc::Free calls were made, but instead IMalloc::Alloc
returned a block which was not freed. For a sketch of code:
class CMallocSpy : public IMallocSpy
{
public:
//...
STDMETHOD_(void*, PostAlloc)(void* block)
{
if (!block)
{
return NULL;
}
if (m_blocks.find(block) != m_blocks.end())
{
ATLASSERT(FALSE); // wrong alloc: this block was not freed yet
}
m_blocks.insert(block);
return block;
}
STDMETHOD_(void*, PreFree)(void* block, BOOL spyed)
{
if (!block)
{
return NULL;
}
if (!spyed)
{
return block;
}
if (m_blocks.find(block) == m_blocks.end())
{
ATLASSERT(FALSE); // wrong free: this block was freed already
}
m_blocks.erase(block);
return block;
}
std::set<void*> m_blocks;
};
The assertion in CMallocSpy::PostAlloc() is triggered eventually...
but how could this be if the one in PreFree() is not?
Or does this means that controls structures of COM allocator are
corrupted?
--
Alex Shulgin