valgrind

下载

wget https://www.valgrind.org/downloads/current.html
tar -jxvf <bz2>

安装

./autogen.sh  # 各种工具例如memcheck,错过这一步会在执行时报错
./configure
./make
./sudo make install  # 拷贝头文件,用于扩展开发,并不会拷贝二进制文件
cp valgrind  /home/me/.local/bin # 全局可用
valgrind -h #  安装正确

测试

#include <stdlib.h>

void f(void) {
  int* x = malloc(10*sizeof(int));
  x[10] =0;
}

int main(void) {
  f();
  return 0;
}

编译和链接

gcc -g -O0 test_valgrind.c

-g打印代码行号

结果

$ valgrind --leak-check=yes a.out
==18951== Memcheck, a memory error detector
==18951== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==18951== Using Valgrind-3.17.0 and LibVEX; rerun with -h for copyright info
==18951== Command: a.out
==18951==
==18951== Invalid write of size 4
==18951==    at 0x40054B: f (test_valgrind.c:5)
==18951==    by 0x40055B: main (test_valgrind.c:9)
==18951==  Address 0x5208068 is 0 bytes after a block of size 40 alloc'd
==18951==    at 0x4C2B087: malloc (vg_replace_malloc.c:380)
==18951==    by 0x40053E: f (test_valgrind.c:4)
==18951==    by 0x40055B: main (test_valgrind.c:9)
==18951==
==18951==
==18951== HEAP SUMMARY:
==18951==     in use at exit: 40 bytes in 1 blocks
==18951==   total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==18951==
==18951== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==18951==    at 0x4C2B087: malloc (vg_replace_malloc.c:380)
==18951==    by 0x40053E: f (test_valgrind.c:4)
==18951==    by 0x40055B: main (test_valgrind.c:9)
==18951==
==18951== LEAK SUMMARY:
==18951==    definitely lost: 40 bytes in 1 blocks
==18951==    indirectly lost: 0 bytes in 0 blocks
==18951==      possibly lost: 0 bytes in 0 blocks
==18951==    still reachable: 0 bytes in 0 blocks
==18951==         suppressed: 0 bytes in 0 blocks
==18951==
==18951== For lists of detected and suppressed errors, rerun with: -s
==18951== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

日志

–log-file=leak.log

结论

编译运行不会报错,但是valgrant检查可以发现内存泄露和地址访问越界

参考

https://blog.youkuaiyun.com/andylauren/article/details/93189740

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值