Search code examples
c++c++11valgrindpoco-libraries

How to fix poco Poco::Net::TCPServerParams() valgrind definite leak


I am using Poco and I am creating TCP server params as below: Poco::Net::TCPServerParams *pParams = new Poco::Net::TCPServerParams();

When I use Valgring, I get definite memory leak: 1271 ==00:00:01:37.131 48682== at 0x4C2903F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so )

at line: Poco::Net::TCPServerParams *pParams = new Poco::Net::TCPServerParams();

Poco version: dpkg -l | grep poco ii libpoco-dev 1.6.1-AVA3 amd64 C++ Portable Components (POCO) Development files ii libpoconet31 1.6.1-AVA3 amd64 C++ Portable Components (POCO) Network library

To fix it, I used delete on the pointer and but I get an error

delete pParams

'TCPServerParams.h:98:10: error: ‘virtual Poco::Net::TCPServerParams::~TCPServerParams()’ is protected'


Solution

  • A common way to use TCPServerParams is that it works with TCPServer together. First you create TCPServerParams by new then it is passed into TCPServer which takes ownership of params. It is described in reference of TCPServer.

    The server also takes ownership of the TCPServerParams object.

    so TCPServer deletes param instance where it is no needed.


    You cannot delete TCPServerParams manually by delete because destructor is protected.

    In Poco library many classes have protected destructor, it forces you to use Poco::AutoPtr class to manage lifetime of instances.

    TCPServerParams derives from RefCountedObject. RefCountedObject provides reference counter mechanism. It has release method which deletes an object when the lifetime of AutoPtr ends.

    So you could write:

    Poco::AutoPtr<Poco::Net::TCPServerParams> p(new Poco::Net::TCPServerParams());
    

    and memory is released automatically by AutoPtr.