valgrind的安装及使用

ubuntu16.04环境下valgrind的安装及使用

1、Valgrind简介

  • Valgrind是运行在Linux上一套基于仿真技术的程序调试和分析工具,它的主要作者是获得过Google-O’Reilly开源大奖的Julian Seward,它包含一个内核——个软件合成的CPU,和一系列的小工具,每个工具都可以完成一项任务──调试,分析,或测试等;
  • Valgrind可以检测内存泄漏和内存违例,还可以分析cache的使用等,灵活轻巧而又强大,能直穿程序错误的心脏,真可谓是程序员的瑞士军刀。

2、安装

sudo apt-get install valgrind

3、使用Memcheck工具进行内存分析

3.1、test.c

#include <stdio.h>
#include <assert.h>
int main(int argc, char *argv[])
{
	char *pchar = (char *)malloc(10 * sizeof(char));
	assert(NULL != pchar);
	pchar[10] = 55;//越界
	//free(pchar);//泄漏
	return 0;
}

3.2、shell command

valgrind --tool=memcheck --leak-check=full --log-file=./log.txt  ./testvalgrind

3.3、log.txt

==86412== Memcheck, a memory error detector
==86412== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==86412== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==86412== Command: ./testvalgrind
==86412== Parent PID: 83051
==86412== 
==86412== Invalid write of size 1
==86412==    at 0x4005BB: main (test.c:7)
==86412==  Address 0x520404a is 0 bytes after a block of size 10 alloc'd
==86412==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==86412==    by 0x40058E: main (test.c:5)
==86412== 
==86412== 
==86412== HEAP SUMMARY:
==86412==     in use at exit: 10 bytes in 1 blocks
==86412==   total heap usage: 1 allocs, 0 frees, 10 bytes allocated
==86412== 
==86412== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==86412==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==86412==    by 0x40058E: main (test.c:5)
==86412== 
==86412== LEAK SUMMARY:
==86412==    definitely lost: 10 bytes in 1 blocks
==86412==    indirectly lost: 0 bytes in 0 blocks
==86412==      possibly lost: 0 bytes in 0 blocks
==86412==    still reachable: 0 bytes in 0 blocks
==86412==         suppressed: 0 bytes in 0 blocks
==86412== 
==86412== For counts of detected and suppressed errors, rerun with: -v
==86412== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
  • log.txt中7、8行提示数组越界错误;
  • log.txt中18、19、20行提示内存泄漏。

4、其他

valgrind -h
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值