Search code examples
c++poco-libraries

Simple Poco TCP networking application core dumping


I'm playing around with Poco at the moment and trying to build a simple TCP server-client application.
The Client's only task in this example is to echo all received data back to the sender.
If I execute the compiled application I get the following message when quitting:

*** Error in `./gameserver': free(): invalid pointer: 0x00007ffd4896cbf8 ***
Aborted (core dumped)

I don't really understand the problem here. I think it has something to do with the Poco part of the code and me missing something important when using the Poco stuff.

Would be nice if someone could tell me what's wrong with my code.

Code:

class Client : public TCPServerConnection
{
public:
    explicit Client(const StreamSocket &socket)
        : TCPServerConnection(socket)
    {
    }

    ~Client()
    {
        socket().close();
    }

    void run()
    {
        char buffer[256];
        int n = socket().receiveBytes(buffer, 256);
        while(n > 0)
        {
            socket().sendBytes(buffer, n);
            n = socket().receiveBytes(buffer, 256);
        }
    }
};

class Factory : public TCPServerConnectionFactory
{
public:
    TCPServerConnection* createConnection(const StreamSocket &socket)
    {
        return new Client(socket);
    }
};

class Server
{
public:
    explicit Server(const string &endpoint)
        : address(endpoint), socket(address), factory(), server(&factory, socket)
    {
        server.start();
    }

    ~Server()
    {
        server.stop();
    }

private:
    SocketAddress address;
    ServerSocket socket;
    TCPServer server;
    Factory factory;
};

int main()
{
    {
        Server server("localhost:5556");
        cin.get();
    }
}

Solution

  • The problem is a double free of the Factory. Both the Server and the TCPServer objects own the Factory, so they both free it when they're done with it.

    The fix is to pick one and let it, and only it, own the factory. Here's one way:

    class Server
    {
    public:
        explicit Server(const string &endpoint)
            : address(endpoint), socket(address), server(new Factory(), socket)
        {
            server.start();
        }
    
        ~Server()
        {
            server.stop();
        }
    
    private:
        SocketAddress address;
        ServerSocket socket;
        TCPServer server;
    };