I have some code here that implements a dynamic memory pool. The pool starts off at size 0 and grows with each successive allocation. It is used to try and minimise the overhead of tons of allocations and de-allocations.
The call to malloc is NOT matched by a call to free. It seems to be relying on the application that uses it to not call enough new's in succession for the application to leak a significant amount of memory.
I did not write it, so this is my best guess.
My question are:
- Is the absence of a call to free a bug or am I missing something to do with overloading the delete operator?
- Is this implementation relying on the OS to clean up the small amount of memory that does leak at exit?
Thanks.
//Obj.h
class Obj
{
public:
Obj(){};
void* operator new(std::size_t size);
void operator delete(void* p);
private:
static std::vector<void*> pool_;
static std::size_t checked_in_;
static std::size_t checked_out_;
};
//Obj.cpp
std::vector<void*> Obj::pool_;
std::size_t Obj::checked_out_ = 0;
std::size_t Obj::checked_in_ = 0;
void* Obj::operator new(std::size_t size)
{
if (pool_.empty())
{
++checked_out_;
return malloc(size);
}
else
{
--checked_in_;
++checked_out_;
void* p = pool_.back();
pool_.pop_back();
return p;
}
}
void Obj::operator delete(void* p)
{
pool_.push_back(p);
if (pool_.size() % 10000 == 0)
{
std::cout<<"mem leak\n";
}
--checked_out_;
++checked_in_;
}