使用gdb调试内存重复释放导致的malloc_error_break错误崩溃

来源:互联网 发布:阿里云邮箱个人 编辑:程序博客网 时间:2024/06/04 20:29

目前使用Poco::Util::ServerApplication构建服务器application,根据Poco官方文档自己扩展Poco::Net::TCPServerConnectionFactory,开启服务器tcp绑定监听。代码片段如下:

Poco::Net::ServerSocket cServerSocket(1300);
FxTcpConnectionFactory cFactory ("127.0.0.1"); 
Poco::Net::TCPServer cServer(&cFactory,cServerSocket);
cServer.start();

代码运行正常,可以正常监听到客户端连接,有一次在终端命令行直接用ctr+c结束进程,结果在服务器结束后给出一段崩溃提示。

ServerMaind(47292,0x7fff76465180) malloc: *** error for object 0x7fff5fbff6e8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

字面上意思是被释放的指针未分配有效内存地址,这是典型的重复释放内存的问题。请出google大神,发现大部分是给出了xcode下如何设置malloc_error_break 符号,我用的是codelite,并不适用,不管他们了,直接进入执行程序所在目录,执行gdb调试命令:

$gdb ./ServerMaind // 开始调试该程序

(gdb) b malloc_error_break // 设置malloc_error_break

(gdb) r // 在调试器中运行ServerMaind,又出同样的错误了,已经被gdb捕捉到了,object 0x7fff5fbff6e8 释放不正常

(gdb) backtrace // 调出崩溃现场的程序调用堆栈

#0  0x00007fff8e58c5b8 in malloc_error_break ()
#1  0x00007fff8e58d972 in free ()
#2  0x0000000100028ca8 in FxTcpConnectionFactory::~FxTcpConnectionFactory (this=0x7fff5fbff6e8) at FxTcpConnectionFactory.cpp:19
#3  0x000000010002afea in Poco::ReleasePolicy<Poco::Net::TCPServerConnectionFactory>::release (pObj=0x7fff5fbff6e8) at SharedPtr.h:90
#4  0x000000010002c9bc in Poco::SharedPtr<Poco::Net::TCPServerConnectionFactory, Poco::ReferenceCounter, Poco::ReleasePolicy<Poco::Net::TCPServerConnectionFactory> >::release (this=0x100e0bc80) at SharedPtr.h:404
#5  0x000000010002ca1e in Poco::SharedPtr<Poco::Net::TCPServerConnectionFactory, Poco::ReferenceCounter, Poco::ReleasePolicy<Poco::Net::TCPServerConnectionFactory> >::~SharedPtr (this=0x100e0bc80) at SharedPtr.h:159
#6  0x00000001001feeb0 in Poco::Net::TCPServerDispatcher::~TCPServerDispatcher (this=0x100e0bb70) at TCPServerDispatcher.cpp:99
#7  0x00000001001fe3bb in Poco::Net::TCPServerDispatcher::release (this=0x100e0bb70) at TCPServerDispatcher.cpp:115
#8  0x00000001001f234b in Poco::Net::TCPServer::~TCPServer (this=0x7fff5fbff648) at TCPServer.cpp:74
#9  0x0000000100029c23 in FxTcpServerMng::main (this=0x100e09aa0, args=@0x100e09ae0) at FxTcpServerMng.cpp:134
#10 0x0000000100212938 in Poco::Util::Application::run (this=0x100e09aa0) at Application.cpp:307
#11 0x0000000100247c2a in Poco::Util::ServerApplication::run (this=0x100e09aa0) at ServerApplication.cpp:117
#12 0x0000000100247a5b in Poco::Util::ServerApplication::run (this=0x100e09aa0, argc=1, argv=0x7fff5fbffae8) at ServerApplication.cpp:628
#13 0x0000000100001497 in main (argc=1, argv=0x7fff5fbffae8) at main.cpp:15
(gdb)

罪魁祸首找到了,原来Poco::Net::TCPServerConnectionFactory用的是共享指针方式来管理内存,而我直接FxTcpConnectionFactory cFactory ("127.0.0.1"),超出作用域就自己释放了,导致程序推出的时候重复释放内存,程序改成如下:

Poco::Net::ServerSocket cServerSocket(1300);
FxTcpConnectionFactory pFactory = new  FxTcpConnectionFactory ("127.0.0.1"); 
Poco::Net::TCPServer cServer(pFactory,cServerSocket);
cServer.start();

再运行后退出,果然正常了。


0 0