0

I am creating a simple(ish) telnet server and am now debugging with valgrind. the code runs great, but valgrind complains about memory lost when the program terminates...and the culprit is the line where I create a new QTcpSocket:

void TelnetConnection::run()
{
    tcpSocketPtr = new QTcpSocket();  // ** remove this due to parent error
    if (!tcpSocketPtr->setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocketPtr->error());
        return;
    }
}

I tried passing 'this' to the QTcpSocket() but then the signal-slots I try to connect complain about being associated with a different parent. Is this the problem? A clue? And...what would the answer be?


I delete/free the tcpsocketptr by assigning it a value of 0 as per below. Is that right?

void TelnetConnection::clientDisconnected()
{
    tcpSocketPtr = 0; // ** Cure memory loss?
    TelnetConnection::s_clientCount--;
    Logger *log =  Logger::instance();
    log->record(Logger::Information,EVENTID_TELNET_DISCONNECTION,"Telnet client "+QString::number(m_clientNumber) +": Disconnecting");
    QThread::quit();  // Exit ths event loop for this thread
}
TSG
  • 4,242
  • 9
  • 61
  • 121

1 Answers1

7

For every time you call "new" you MUST call "delete." As the comments have suggested, you point the pointer to 0, but never call delete.

Edited to add a YT video of a good explanation of the concepts: http://www.youtube.com/watch?v=_749lj2yb8Y Essentially you are never freeing the memory you request from the CPU, hence you memory leak. A simple call to delete will solve this.

It'sPete
  • 5,083
  • 8
  • 39
  • 72
  • 1
    Wow - big wrong assumption on my part...I thought c++ had a heap manager that cleaned up after me. I'll have to use delete. Thanks. – TSG Oct 09 '13 at 14:45