问题
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