valgrind工具功能很多,可以动态检测程序运行时的问题,其中一项就是检测内存泄漏。
使用方法: valgrind [options] prog-and-args
用例:
问题程序代码: memleak.c
#include <stdio.h>
#include <stdlib.h>
main(int argc, char **argv)
{
char *p = malloc(5);
char *q = malloc(10);
free(p);
//free(q);
return;
}
运行程序: valgrind ./memleak
输出结果:
==17823== Memcheck, a memory error detector
==17823== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==17823== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==17823== Command: ./memleak
==17823==
==17823==
==17823== HEAP SUMMARY:
==17823== in use at exit: 10 bytes in 1 blocks
==17823== total heap usage: 2 allocs, 1 frees, 15 bytes allocated
==17823==
==17823== LEAK SUMMARY:
==17823== definitely lost: 10 bytes in 1 blocks
==17823== indirectly lost: 0 bytes in 0 blocks
==17823== possibly lost: 0 bytes in 0 blocks
==17823== still reachable: 0 bytes in 0 blocks
==17823== suppressed: 0 bytes in 0 blocks
==17823== Rerun with --leak-check=full to see details of leaked memory
==17823==
==17823== For counts of detected and suppressed errors, rerun with: -v
==17823== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 7)
红色字体部分显示程序有两次动态内存分配,共15个字节,只free了一次,内存泄漏10个字节
valgrind缺点:
目前好像只适用于GNU/LINUX x86平台