版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38954835/article/details/87881205
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