Memory detection memcheck of linux code detection tool valgrind

1. Installation command:

$ sudo apt-get install valgrind

The installation is successful as follows:

 Check the version command: $ valgrind --version 

2. Introduction to valgrind detection tool tool

(1) Memcheck is a memory error detector.

(2) Cachegrind is a cache and branch prediction analyzer.

(3) Callgrind is a tool for checking problems in the program function call process.

(4) Helgrind is a tool for detecting errors in multi-threaded programs.

 Commonly used detection tools include the above. The tools installed in this article are as follows:

3. Usage of memory detection tool memcheck

Use the command:

//方法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;
}

 Using the detection tool memcheck detection results are as follows:

Result analysis:

 You can see a memory leak of 1024 bytes at the line drawn above, and the code is in line 10 of main.cpp.

The official website explains the above leak summary classification as follows:

  • “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.

It can be seen that "definitely lost" must need to be repaired. Indirectly lost "indirectly lost", if the absolute loss is fixed, the indirect loss should disappear.

Additional knowledge:

1. Official website knowledge: Valgrind Home

2. Installation and use of linux valgrind_Zhongyl_'s Blog-CSDN Blog 

3. Introduction to the basic functions of valgrind and instructions on how to use it

4. valgrind and vgdb use: Can valgrind output a partial report without exiting the profile application? _RyanLeiWang's Blog - CSDN Blog 

Guess you like

Origin blog.csdn.net/hanxiaoyong_/article/details/130254896