Giter VIP home page Giter VIP logo

Comments (3)

yuesong-feng avatar yuesong-feng commented on May 3, 2024

多谢,应该是!=,你可以提交一个PR修复

from 30daymakecppserver.

jon2180 avatar jon2180 commented on May 3, 2024

你好,我仿照你的教程写了自己的版本,修复了这个问题( == 改成了 != )。但似乎存在另外一个问题。看这个析构函数,这个 socket 是应该及时回收的。

然后我查阅了下面这一段代码

Socket *clnt_sock = new Socket(serv_sock->accept(clnt_addr)); //会发生内存泄露!没有delete
printf("new client fd %d! IP: %s Port: %d\n", clnt_sock->getFd(), inet_ntoa(clnt_addr->addr.sin_addr), ntohs(clnt_addr->addr.sin_port));
clnt_sock->setnonblocking();
Channel *clntChannel = new Channel(loop, clnt_sock->getFd());
std::function<void()> cb = std::bind(&Server::handleReadEvent, this, clnt_sock->getFd());
clntChannel->setCallback(cb);
clntChannel->enableReading();

根据我的理解,这段代码没有回收 socket 的空间,却也没有维护 socket 指针,似乎必然存在内存泄露。 我尝试在自己的版本中使用了智能指针。

// excerpt
auto clientSocket = std::make_shared<Socket>(serverSock->Accept( /* omit */ ));

程序在处理事件时,正确地释放了 clientSocket 的内存,但相应地造成自动关闭了客户端连接,移除了epoll 对 serverSock->Accept() 返回的 socket 连接的监听。

我自己的临时解决方案是在类中设置了一个属性 bool autoRelease_ 来控制是否自动关闭连接。

我有些疑惑,这些 socket 对象是作为临时对象存在吗,是否有维护起来的必要呢?

from 30daymakecppserver.

yuesong-feng avatar yuesong-feng commented on May 3, 2024

所有客户端Socket都不是临时对象,需要由Connection类维护、管理生命周期,在day08的教程里会处理。另外day13后的版本不会有任何内存泄漏问题,前面的代码重点放在架构上,忽略了一些细节。

from 30daymakecppserver.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.