我写了一个套接字服务器。而且我意识到,当我在运行Ctrl-C时按下它时,可能会发生内存泄漏。我用valgrind找到了。

我的服务器代码很简单。基本上,我创建一个Listener对象,启动一个线程以接受连接并尝试加入该线程:

 try {
    Server::Listener listener(1234);

    boost::thread l(boost::bind(&Server::Listener::start, &listener));

    l.join();

} catch(exception& e) {
    cout<<e.what()<<endl;
}


当我运行valgrind时,它给了我:

== 3580 ==命令:bin / Debug / p_rpc
== 3580 ==
列表器已启动...
循环中
^ C == 3580 ==
== 3580 ==堆摘要:
== 3580 ==在出口使用:24块中的3176个字节
== 3580 ==总堆使用量:28个分配,4个空闲,4,328个字节分配
== 3580 ==
== 3580 ==丢失记录21之24中可能会丢失1个块中的288个字节
== 3580 ==在0x4C29E46:calloc(在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
== 3580 ==通过0x4012084:_dl_allocate_tls(dl-tls.c:297)
== 3580 ==通过0x4E3AABC:pthread_create @@ GLIBC_2.2.5(allocatestack.c:571)
== 3580 ==通过0x5260F9F:boost :: thread :: start_thread()(在/usr/lib/libboost_thread.so.1.49.0中)
== 3580 ==通过0x407B93:boost :: thread :: thread,boost :: _ bi :: list1>>>(boost :: _ bi :: bind_t,boost :: _ bi :: list1>> &&)(thread.hpp :171)
== 3580 ==通过0x404CA4:main(main.cpp:179)
== 3580 ==
== 3580 ==泄漏摘要:
== 3580 ==绝对丢失:0字节,位于0块中
== 3580 ==间接丢失:0字节(0块)
== 3580 ==可能丢失:1个块中的288个字节
== 3580 ==仍可到达:2,888字节,共23块
== 3580 ==已抑制:0字节,0块
== 3580 ==未显示可访问的块(找到指针的块)。
== 3580 ==要查看它们,请重新运行:--leak-check = full --show-reachable = yes
== 3580 ==
== 3580 ==有关检测到和抑制的错误的计数,请重新运行:-v
== 3580 ==错误摘要:1个上下文中有1个错误(抑制:2个中有2个)
被杀


指出可能有288字节丢失。我想我可以使用信号处理程序来释放此资源。但是我不知道该怎么做。你能给我一个例子吗?

干杯,
埃尔顿

最佳答案

进程关闭时,操作系统会自动清除该进程拥有的所有内存。您无需担心程序退出时释放该内存。 The building is being demolished. Don't bother sweeping the floor and emptying the trash cans and erasing the whiteboards. And don't line up at the exit to the building so everybody can move their in/out magnet to out. All you're doing is making the demolition team wait for you to finish these pointless housecleaning tasks.

您需要担心的那种泄漏是那些在程序生命周期中不断泄漏的泄漏。

关于c++ - 使用信号处理程序释放资源?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14593485/

10-09 17:28