Qt/C++ QTcpSocket causes memory leak, not sure why

别来无恙 提交于 2019-12-10 12:17:21

问题


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
}

回答1:


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.



来源:https://stackoverflow.com/questions/19264500/qt-c-qtcpsocket-causes-memory-leak-not-sure-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!