Qt / C ++ QTcpSocket导致内存泄漏,不知道为什么 [英] Qt/C++ QTcpSocket causes memory leak, not sure why

查看:233
本文介绍了Qt / C ++ QTcpSocket导致内存泄漏,不知道为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个简单的(ish)telnet服务器,我现在正在使用valgrind调试。代码运行得很好,但是valgrind抱怨程序终止时的内存丢失...并且罪魁祸首是我创建一个新的QTcpSocket的行:

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;
    }
}



我尝试将'this'传递给QTcpSocket但随后我试图连接的信号槽抱怨与不同的父亲关联。这是问题吗?线索?

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?

我删除/释放tcpsocketptr,赋值为0每下。是这样吗?

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
}


推荐答案

每次您呼叫「新」时,都必须呼叫「删除」。

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.

编辑以添加一个对这些概念有很好解释的YT视频: http://www.youtube.com/watch?v=_749lj2yb8Y 基本上你永远不会释放你从CPU请求的内存,因此你的内存泄漏。一个简单的删除呼叫将解决这个问题。

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.

这篇关于Qt / C ++ QTcpSocket导致内存泄漏,不知道为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆