I am trying to find out the total memory allocated and later freed by my program to figure out if there are any memory leaks by overloading the new and delete operators. Below are the overloaded methods of new and delete:
void* operator new(size_t sz)
{
void* m = (void*) MemoryManager::getInstance()->allocate(sz, false);
if(!m){
throw std::bad_alloc{};
}
return m;
}
// Overloading Global delete operator
void operator delete(void* m) noexcept
{
MemoryManager::getInstance()->deallocate(m, false);
}
The allocate and deallocate methods that new and delete are calling are defined as below:
PointerType allocate(size_t size, bool isArray){
PointerType newPtr = (PointerType)std::malloc(size);
mMemKeeper[newPtr] = size;
mBytes += size;
return newPtr;
}
void MemoryManager::deallocate(void* pt, bool isArray){
LockGuard lck(mGateKeeper);
if(mMemKeeper.find((PointerType)pt) != mMemKeeper.end()){
mBytes -= mMemKeeper[(PointerType)pt];
mMemKeeper.erase((PointerType)pt);
std::free(pt);
}
}
typedef char* PointerType;
typedef std::unordered_map<PointerType, MemoryInfo,
std::hash<PointerType>, std::equal_to<PointerType>,
my_allocator<std::pair<const PointerType, MemoryInfo> > > OrderedMap;
OrderedMap mMemKeeper;
The issue I am facing is in deallocate while accessing mMemKeeper.find((PointerType)pt)
. Seems like the pointer pt
is already deallocated by the time it reaches here and dereferencing it is causing problems. When can this happen and is there a way I can detect if memory of pt
is already freed?