您现在的位置是:首页 >其他 >linux代码检测工具valgrind之内存检测memcheck网站首页其他

linux代码检测工具valgrind之内存检测memcheck

夜雨听萧瑟 2023-05-26 00:00:02
简介linux代码检测工具valgrind之内存检测memcheck

1、安装命令:

$ sudo apt-get install valgrind

安装成功如下:

 检测版本命令:$ valgrind --version 

2、valgrind检测工具tool介绍

(1)Memcheck是一个内存错误检测器。

(2)Cachegrind是缓存和分支预测分析器。

(3) Callgrind检查程序函数调用过程出现问题的工具。

(4) Helgrind是检测多线程程序出现错误的工具。

 常用的检测工具有上面几个,本文安装的工具如下:

3、内存检测工具memcheck用法

使用命令:

//方法1: 直接输出到控制台
valgrind --tool=memcheck --leak-check=full ./test //test为程序名

//方法2: 重定向到文件中log.txt中
valgrind --tool=memcheck --log-file=./log.txt  --leak-check=full  ./test 

demo

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World!" << endl;

    {
    char* pSubject = new char[1*1024];
    }
    return 0;
}

 使用检测工具memcheck检测结果如下:

结果分析:

 上面画线地方可以看到内存泄漏1024字节,代码在main.cpp的第10行。

官网对上面泄漏总结分类解释如下:

  • “definitely lost” means your program is leaking memory – fix those leaks!
  • “indirectly lost” means your program is leaking memory in a pointer-based structure. (E.g. if the root node of a binary tree is “definitely lost”, all the children will be “indirectly lost”.) If you fix the “definitely lost” leaks, the “indirectly lost” leaks should go away.
  • “possibly lost” means your program is leaking memory, unless you’re doing unusual things with pointers that could cause them to point into the middle of an allocated block; see the user manual for some possible causes. Use --show-possibly-lost=no if you don’t want to see these reports.
  • “still reachable” means your program is probably ok – it didn’t free some memory it could have. This is quite common and often reasonable. Don’t use --show-reachable=yes if you don’t want to see these reports.
  • “suppressed” means that a leak error has been suppressed. There are some suppressions in the default suppression files. You can ignore suppressed errors.

可以看出绝对丢失的“definitely lost”必须需要修复。间接丢失“indirectly lost“,如果修复了绝对丢失,则间接丢失应该消失。

附加知识:

1、官网知识:Valgrind Home

2、linux valgrind 安装和使用_Zhongyl_的博客-CSDN博客 

3、valgrind基本功能介绍、基础使用方法说明_valgrind 使用_HNU Latecomer的博客-CSDN博客

4、valgrind和vgdb使用:valgrind可以输出部分报告而无需退出配置文件应用程序吗?_RyanLeiWang的博客-CSDN博客 

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。