使用Valgrind检测内存泄露

使用Valgrind检测内存泄露

  • 环境
  • 测试
  • 参考文章

环境

kali2021

apt install valgrind

测试

#include
void f(void)
{
int* x = malloc(10 * sizeof(int));
x[10] = 0; //问题1: 数组下标越界
} //问题2: 内存没有释放
int main(void)
{
f();
return 0;
}
gcc -g -o test 1.c

cmake时候使用

cmake  -DCMAKE_BUILD_TYPE=Debug ..
valgrind --tool=memcheck --leak-check=full ./test
┌──(rootlinux)-[~]
└─# valgrind --tool=memcheck --leak-check=full ./test
==2656== Memcheck, a memory error detector
==2656== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2656== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==2656== Command: ./test
==2656== 
==2656== Invalid write of size 4
==2656==    at 0x109153: f (1.c:5)
==2656==    by 0x109164: main (1.c:9)
==2656==  Address 0x4a2a068 is 0 bytes after a block of size 40 alloc'd
==2656==    at 0x48397B5: malloc (vg_replace_malloc.c:381)
==2656==    by 0x109146: f (1.c:4)
==2656==    by 0x109164: main (1.c:9)
==2656== 
==2656== 
==2656== HEAP SUMMARY:
==2656==     in use at exit: 40 bytes in 1 blocks
==2656==   total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==2656== 
==2656== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2656==    at 0x48397B5: malloc (vg_replace_malloc.c:381)
==2656==    by 0x109146: f (1.c:4)
==2656==    by 0x109164: main (1.c:9)
==2656== 
==2656== LEAK SUMMARY:
==2656==    definitely lost: 40 bytes in 1 blocks
==2656==    indirectly lost: 0 bytes in 0 blocks
==2656==      possibly lost: 0 bytes in 0 blocks
==2656==    still reachable: 0 bytes in 0 blocks
==2656==         suppressed: 0 bytes in 0 blocks
==2656== 
==2656== For lists of detected and suppressed errors, rerun with: -s
==2656== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

可以看到有40字节的大小没有被释放,正好是10*4(int)大小

参考文章

https://blog.csdn.net/mafuli007/article/details/8083334

你可能感兴趣的:(编程开发,内存泄漏)