一、安装valgrind
安装valgrind,正常的三部曲configure/make/make install就行。
二、memchk使用
1、执行命令
[root@10g-host4 tools]# valgrind --track-fds=yes --log-file=memchk-svr.log --tool=memcheck --leak-check=full --show-reachable=yes ./udp-pacing/valgrind_svr
2、查看日志
185 ==29107== 208 bytes in 1 blocks are definitely lost in loss record 9 of 12
186 ==29107== at 0x4A05FEF: calloc (vg_replace_malloc.c:711)
187 ==29107== by 0x4030F4: wmp_sender_init (wmp_impl.c:237)
188 ==29107== by 0x4034B5: wmp_socket_new_impl (wmp_impl.c:327)
189 ==29107== by 0x4069D6: handle_packet (wmp_impl.c:1434)
190 ==29107== by 0x406D2E: wmp_socket_notify_packet (wmp_impl.c:1500)
191 ==29107== by 0x409DC2: udp_recvfrom (pt_session_udp.c:321)
192 ==29107== by 0x415487: event_process_active_single_queue (event.c:1346)
193 ==29107== by 0x415487: event_process_active (event.c:1416)
194 ==29107== by 0x415487: event_base_loop (event.c:1617)
195 ==29107== by 0x402839: main (valgrind_svr.c:167)
3、分析日志
“definitely lost ”这是说明确定无疑地发生了内存泄露。
wmp_impl.c:237 sender_t *s = calloc(1, sizeof(sender_t));
wmp_sender_init()函数名,在237行申请了内存空间,却没有释放。
三、callgrind
1、执行命令
[root@10g-host4 tools]# valgrind --tool=callgrind ./udp-pacing/valgrind_svr
[root@10g-host4 udp-pacing]# ps -ef | grep valgrind
root 29980 13926 5 11:06 pts/0 00:00:01 valgrind --tool=callgrind ./udp-pacing/valgrind_svr
root 29984 28594 0 11:06 pts/1 00:00:00 grep valgrind
[root@10g-host4 udp-pacing]# kill -USR1 29980 发送信号给应用进程
[root@10g-host4 udp-pacing]# ps -ef | grep valgrind
root 30012 28594 0 11:06 pts/1 00:00:00 grep valgrind
[root@10g-host4 tools]# ll callgrind.out.29980
-rw------- 1 root root 73177 Jan 6 11:06 callgrind.out.29980
2、打印图形
到官方网站下载最新gprof2dot.py程序,旧版本不支持某些参数,https://github.com/jrfonseca/gprof2dot。
[root@10g-host4 tools]#valgrind --tool=callgrind ./udp-pacing/ut_cmp_server
[root@10g-host4 tools]# python gprof2dot-2015.12.1/gprof2dot.py -f callgrind callgrind.out.29980 -z main -e0 -n0 > callgrind.out
[root@10g-host4 tools]# dot -Tjpg callgrind.out -o call.jpg