使用Valgrind检测内存泄露

使用Valgrind检测内存泄露

环境

kali2021

apt install valgrind

测试

#include<stdlib.h>
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
┌──(root💀linux)-[~]
└─# 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值