安装
centos:
yum install valgrind
确认是否安装正确:
valgrind --version
编译程序
打开调试模式,加上-g参数
内存泄漏检测
使用
valgrind --leak-check=yes ./test
显示详细的内存泄漏信息:
valgrind --leak-check=full ./test
输出
#include <stdlib.h>
  void memleak(void)
  {
     int* arr = malloc(1024 * sizeof(int));
  }
  int main(void)
  {
     memleak();
     return 0;
  }
[root@com1 test]# valgrind --leak-check=yes ./test
==1040518== Memcheck, a memory error detector
==1040518== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==1040518== Using Valgrind-3.21.0 and LibVEX; rerun with -h for copyright info
==1040518== Command: ./test
==1040518== 
==1040518== 
==1040518== HEAP SUMMARY:
==1040518==     in use at exit: 4,096 bytes in 1 blocks
==1040518==   total heap usage: 1 allocs, 0 frees, 4,096 bytes allocated
==1040518== 
==1040518== 4,096 bytes in 1 blocks are definitely lost in loss record 1 of 1
==1040518==    at 0x4C2B129: malloc (vg_replace_malloc.c:431)
==1040518==    by 0x40052E: memleak (test.c:5)
==1040518==    by 0x40053D: main (test.c:10)
==1040518== 
==1040518== LEAK SUMMARY:
==1040518==    definitely lost: 4,096 bytes in 1 blocks
==1040518==    indirectly lost: 0 bytes in 0 blocks
==1040518==      possibly lost: 0 bytes in 0 blocks
==1040518==    still reachable: 0 bytes in 0 blocks
==1040518==         suppressed: 0 bytes in 0 blocks
==1040518== 
==1040518== For lists of detected and suppressed errors, rerun with: -s
==1040518== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
[root@com1 test]# valgrind --leak-check=full ./test
==1040570== Memcheck, a memory error detector
==1040570== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==1040570== Using Valgrind-3.21.0 and LibVEX; rerun with -h for copyright info
==1040570== Command: ./test
==1040570== 
==1040570== 
==1040570== HEAP SUMMARY:
==1040570==     in use at exit: 4,096 bytes in 1 blocks
==1040570==   total heap usage: 1 allocs, 0 frees, 4,096 bytes allocated
==1040570== 
==1040570== 4,096 bytes in 1 blocks are definitely lost in loss record 1 of 1
==1040570==    at 0x4C2B129: malloc (vg_replace_malloc.c:431)
==1040570==    by 0x40052E: memleak (test.c:5)
==1040570==    by 0x40053D: main (test.c:10)
==1040570== 
==1040570== LEAK SUMMARY:
==1040570==    definitely lost: 4,096 bytes in 1 blocks
==1040570==    indirectly lost: 0 bytes in 0 blocks
==1040570==      possibly lost: 0 bytes in 0 blocks
==1040570==    still reachable: 0 bytes in 0 blocks
==1040570==         suppressed: 0 bytes in 0 blocks
==1040570== 
==1040570== For lists of detected and suppressed errors, rerun with: -s
==1040570== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)