Linux下检测程序内存泄漏
工具:valgrind
Linux下载方式:yum install valgrind
内存泄漏:程序在heap上分配了内存却没有释放
写一个c语言内存泄漏程序:
#include <stdlib.h>
void f()
{
int *t=malloc(sizeof(int)*10);
}
int main()
{
int *array = malloc(10*sizeof(int));
f();
return 0;
}
很简单的一个程序,f()和main中都有malloc申请内存但是没有释放,故运行该程序会造成内存泄漏。
编译后生成a.out文件: gcc -g -o a.out test.c
运用valgrind检测内存泄漏:
valgrind --tool=memcheck --leak-check=full ./a.out
运行结果:
[root@jessy /]# valgrind --tool=memcheck --leak-check=full ./a.out
==14588== Memcheck, a memory error detector
==14588== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==14588== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==14588== Command: ./a.out
==14588==
==14588==
==14588== HEAP SUMMARY:
==14588== in use at exit: 80 bytes in 2 blocks
==14588== total heap usage: 2 allocs, 0 frees, 80 bytes allocated
==14588==
==14588== 40 bytes in 1 blocks are definitely lost in loss record 1 of 2
==14588== at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==14588== by 0x400556: main (test.c:8)
==14588==
==14588== 40 bytes in 1 blocks are definitely lost in loss record 2 of 2
==14588== at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==14588== by 0x40053E: f (test.c:4)
==14588== by 0x400564: main (test.c:9)
==14588==
==14588== LEAK SUMMARY:
==14588