主要有两种方法:
一是用gdb,二是用valgrind
1.先用 ulimit -c unlimited 设置环境
2.重新运行程序,等待 segment fault,应该会生成 core 文件
3.gdb core*
以下是gdb ./UserStatsControl core.12345的输出
#0 0x00000000 in ?? ()
(gdb) bt
#0 0x00000000 in ?? ()
#1 0x00ab9854 in SP_EventCallback::onWrite (fd=20, events=4, arg=0xb5100470) at
speventcb.cpp:190
#2 0x008bc540 in event_base_loop (base=0x90dd3f0, flags=Variable "flags" is not available.
) at event.c:315
#3 0x00abb3ed in SP_Server::start (this=0xbffd0de0) at spserver.cpp:236
#4 0x00abaf17 in SP_Server::eventLoop (arg=0xbffd0de0) at spserver.cpp:118
#5 0x00abaef1 in SP_Server::runForever (this=0xbffd0de0) at spserver.cpp:109
#6 0x0804bb9b in main (argc=1, argv=0xbffd0f84) at UserStatsControl.cpp:71
可知是speventcb.cpp:190 一行引起的问题。
还有一个专用工具valgrind ,专门用来检查c++内存泄漏等问题,http://valgrind.org/
以下是valgrind --leak-check=yes ./UserStatsControl的输出:
UserStatsControl[14440]: userCollectD connected(20.38): 192.168.14.11
==14440== Invalid read of size 4
==14440== at 0x402C470: SP_EventCallback::onRead(int, short, void*) (speventcb.cpp:106)
==14440== by 0x400D53F: event_base_loop (event.c:315)
==14440== by 0x402E3EC: SP_Server::start() (spserver.cpp:236)
==14440== by 0x402DF16: SP_Server::eventLoop(void*) (spserver.cpp:118)
==14440== by 0x402DEF0: SP_Server::runForever() (spserver.cpp:109)
==14440== by 0x804BB32: main (UserStatsControl.cpp:71)
==14440== Address 0x63373C8 is 0 bytes inside a block of size 8 free'd
==14440== at 0x400518E: operator delete(void*) (vg_replace_malloc.c:246)
==14440== by 0x4029AEE: SP_DefaultMsgDecoder::~SP_DefaultMsgDecoder()
(spmsgdecoder.cpp:29)
==14440== by 0x402ACFF: SP_Request::setMsgDecoder(SP_MsgDecoder*) (sprequest.cpp:31)
==14440== by 0x804C065: UserStatsHandler::start(SP_Request*, SP_Response*)
(UserStatsHandler.cpp:22)
==14440== by 0x402D5FE: SP_EventHelper::start(void*) (speventcb.cpp:472)
==14440== by 0x402AEF0: SP_SimpleTask::run() (spexecutor.cpp:56)
==14440== by 0x402B501: SP_Executor::worker(void*) (spexecutor.cpp:158)
==14440== by 0x40280DE: SP_ThreadPool::wrapperFunc(void*) (spthreadpool.cpp:154)
==14440== by 0x38E370: start_thread (in /lib/tls/libpthread-2.3.4.so)
==14440== by 0x2F8FFD: clone (in /lib/tls/libc-2.3.4.so)
pure virtual method called
terminate called without an active exception