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:
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_;
}
The missing 'free' means that you cannot embed this in some larger application, start it up, shut it down, and end up back where you started. This is fine if you control the entire application, and not fine if this code has to, in fact, be embeddable. To make that work, you would need some entrypoint that walks the vector calling free.
It never leaks in the conventional sense, since each malloc'ed chunk is stored in the vector by operator delete for re-use, and the operator delete complains if it sees too many items in the vector.