c++ - 使用信号处理程序释放资源?

标签 c++ valgrind

我写了一个套接字服务器。我意识到当我在它运行时按下 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 个 block 中的 3,176 个字节
==3580== 堆总使用量:28 次分配,4 次释放,分配了 4,328 字节
==3580==
==3580== 1个 block 中的288个字节可能丢失在丢失记录21 of 24
==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 (allocastack.c:571)
==3580== 0x5260F9F:boost::thread::start_thread()(在
/usr/lib/libboost_thread.so.1.49.0 中) ==3580== by 0x407B93: boost::thread::thread, boost::_bi::list1 >> >(boost::_bi::bind_t, boost::_bi::list1 >>&&) (thread.hpp :171)
==3580== by 0x404CA4: main (main.cpp:179)
==3580==
==3580== 泄漏摘要:
==3580== 绝对丢失:0 个 block 中的 0 个字节
==3580== 间接丢失:0 个 block 中的 0 个字节
==3580== 可能丢失:1 个 block 中的 288 个字节
==3580== 仍然可以访问:23 个 block 中的 2,888 字节
==3580== 抑制:0 个 block 中的 0 个字节
==3580== 未显示可到达的 block (找到指针的 block )。
==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/

相关文章:

c - stack 未初始化的值是由堆栈分配创建的

c++ - Valgrind 是否有像 Purify/Quantify 这样的 API 可以让你禁用数据记录?

c - 为什么 GDB 在到达 `main` 之前不能解析这个符号?为什么 valgrind 根本无法解决它?

c++ - 为什么 MinGW-w64 生成 32 位二进制文​​件?

c++ - 从 UUID 中提取 MAC 地址

带有 ostream 和 istream 的 c++ vector

c - Valgrind 检测到可到达的泄漏,它们在哪里?

c - Malloc 的 char 数组有意外的输出

c++ 缺少一些输出结果

c++ - OpenGL多子窗口问题