今天想检测自己写的一段代码有没有内存泄露,于是想到了googleperf和vagrind,对比了一下,vagrind能检测出一处内存泄露,而googleperf却没有,不知道是什么原因,这两个工具的原理也不太一样,vagrind的在自己的模拟环境下跑的,而googleperf是通过链接自己的tcmalloc的方式来实现。
vagrind检测内存泄露的方法是这样的:
方法
valgrind --leak-check=full ./sx_utils
结果
==16466== Memcheck, a memory error detector
==16466== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==16466== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==16466== Command: ./sx_utils
==16466==
==16466==
==16466== HEAP SUMMARY:
==16466== in use at exit: 776 bytes in 26 blocks
==16466== total heap usage: 57 allocs, 31 frees, 30,560 bytes allocated
==16466==
==16466== 360 (240 direct, 120 indirect) bytes in 10 blocks are definitely lost in loss record 8 of 8
==16466== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16466== by 0x4E9DF77: CRYPTO_malloc (in /usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2)
==16466== by 0x4F4B869: BUF_MEM_new (in /usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2)
==16466== by 0x4F4CEC8: ??? (in /usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2)
==16466== by 0x4F4BE91: BIO_set (in /usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2)
==16466== by 0x4F4BF01: BIO_new (in /usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2)
==16466== by 0x400CE5: sx_base64_encode (sx_utils.c:54)
==16466== by 0x400EEC: main (sx_utils.c:95)
==16466==
==16466== LEAK SUMMARY:
==16466== definitely lost: 240 bytes in 10 blocks
==16466== indirectly lost: 120 bytes in 10 blocks
==16466== possibly lost: 0 bytes in 0 blocks
==16466== still reachable: 416 bytes in 6 blocks
==16466== suppressed: 0 bytes in 0 blocks
==16466== Reachable blocks (those to which a pointer was found) are not shown.
==16466== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==16466==
==16466== For counts of detected and suppressed errors, rerun with: -v
==16466== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
分析
上面我们能够看到,sx_utils.c文件的54行BIO_new的一个东西中,BUF_MEM_new的内存没有释放,通过查看代码,的确是这样的,释放掉了就好了。