一个查看堆内存泄露的工具

valgrind

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 
 4 void f(void)
 5 {
 6     int *x = malloc(10 * sizeof(int));
 7     x[10] = 0;
 8 }
 9 int main(void)
10 {
11     f();
12     return 0;
13 }
测试代码

控制台:

 

 

==4642== Memcheck, a memory error detector
==4642== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4642== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==4642== Command: ./a
==4642==
==4642== Invalid write of size 4
==4642== at 0x10916B: f (a.c:7)
==4642== by 0x109180: main (a.c:11)
==4642== Address 0x4a50068 is 0 bytes after a block of size 40 alloc'd
==4642== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4642== by 0x10915E: f (a.c:6)
==4642== by 0x109180: main (a.c:11)
==4642==
==4642==
==4642== HEAP SUMMARY:
==4642== in use at exit: 40 bytes in 1 blocks
==4642== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==4642==
==4642== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4642== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4642== by 0x10915E: f (a.c:6)
==4642== by 0x109180: main (a.c:11)
==4642==
==4642== LEAK SUMMARY:
==4642== definitely lost: 40 bytes in 1 blocks
==4642== indirectly lost: 0 bytes in 0 blocks
==4642== possibly lost: 0 bytes in 0 blocks
==4642== still reachable: 0 bytes in 0 blocks
==4642== suppressed: 0 bytes in 0 blocks
==4642==
==4642== For lists of detected and suppressed errors, rerun with: -s
==4642== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

posted @ 2022-09-26 18:04  星明勇往直前  阅读(35)  评论(0)    收藏  举报