内存泄漏工具valgrind在线安装及使用
linux版本ubuntu18.04
在线安装命令
sudo apt install valgrind
使用工具检测内存泄漏:
//产生内存泄漏代码
//test.c
#include <head.h>
int main(int argc, char **argv)
{
int *p = (int*)malloc(10);
return 0;
}
//gcc -g test.c(如果不加-g选项,工具不会报发生泄漏的代码行数) 生成 a.out;
//使用工具检测内存泄漏问题
valgrind --tool=memcheck --leak-check=full ./a.out
==35336== Memcheck, a memory error detector
==35336== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==35336== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==35336== Command: ./a.out
==35336==
==35336==
==35336== HEAP SUMMARY:
==35336== in use at exit: 10 bytes in 1 blocks
==35336== total heap usage: 1 allocs, 0 frees, 10 bytes allocated
==35336==
==35336== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==35336== at 0x4C31B0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==35336== by 0x108662: main (test.c:5)
==35336==
==35336== LEAK SUMMARY:
==35336== definitely lost: 10 bytes in 1 blocks
==35336== indirectly lost: 0 bytes in 0 blocks
==35336== possibly lost: 0 bytes in 0 blocks
==35336== still reachable: 0 bytes in 0 blocks
==35336== suppressed: 0 bytes in 0 blocks
==35336==
==35336== For counts of detected and suppressed errors, rerun with: -v
==35336== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
可以看到有对泄漏信息进行检测,并且指出产生泄漏的代码及代码行数,还是比较方便的。