linux内存泄漏检测valgrind

valgrind 检查内存泄漏 Linux 下

1、安装

sudo apt-get install valgrind

2、使用

先用qt或者g++对代码编译

然后对编译后的文件

生成可执行程序test之后,如何使用Valgrind来生成内存的记录文件呢?一般这样使用:

valgrind --leak-check=full --log-file=test_valgrind.log --num-callers=30 ./test

–log-file 后面的test_valgrind.log是指定生成的日志文件名称。

–num-callers 后面的60是生成的每个错误记录的追踪行数。30是随便设定的,如果没指定,默认是12行貌似(有可能有的追踪行就没显示)。

–leak-check=full 表示开启详细的内存泄露检测器。

3、内存检查

 valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./ptreigen 
#include <iostream>
#include <cstdlib>

#include <memory>
using namespace std;

int main()
{

    int *p = new int(10);
   // auto_ptr<int>pa(p);
    //cout <<*pa <<endl;

    cout << "Hello World!" << endl;
    return 0;
}
==7474== Memcheck, a memory error detector
==7474== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7474== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==7474== Command: ./ptreigen
==7474== 
Hello World!
==7474== 
==7474== HEAP SUMMARY:
==7474==     in use at exit: 4 bytes in 1 blocks
==7474==   total heap usage: 3 allocs, 2 frees, 73,732 bytes allocated
==7474== 
==7474== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==7474==    at 0x4C3217F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7474==    by 0x10890B: main (main.cpp:10)
==7474== 
==7474== LEAK SUMMARY:
==7474==    definitely lost: 4 bytes in 1 blocks
==7474==    indirectly lost: 0 bytes in 0 blocks
==7474==      possibly lost: 0 bytes in 0 blocks
==7474==    still reachable: 0 bytes in 0 blocks
==7474==         suppressed: 0 bytes in 0 blocks
==7474== 
==7474== For counts of detected and suppressed errors, rerun with: -v
==7474== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

可以看出内存泄漏处,一个位置报错

4、修改

#include <iostream>
#include <cstdlib>

#include <memory>
using namespace std;

int main()
{

    int *p = new int(10);
    auto_ptr<int>pa(p);
    //cout <<*pa <<endl;

    cout << "Hello World!" << endl;
    return 0;
}

引入智能指针修改

s@ls-vpc:~/heima/3c++/8/build-ptreigen-unknown-Debug$ valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./ptreigen 
==7524== Memcheck, a memory error detector
==7524== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7524== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==7524== Command: ./ptreigen
==7524== 
Hello World!
==7524== 
==7524== HEAP SUMMARY:
==7524==     in use at exit: 0 bytes in 0 blocks
==7524==   total heap usage: 3 allocs, 3 frees, 73,732 bytes allocated
==7524== 
==7524== All heap blocks were freed -- no leaks are possible
==7524== 
==7524== For counts of detected and suppressed errors, rerun with: -v
==7524== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

    原文作者:xxxx追风
    原文地址: https://blog.csdn.net/m0_50068884/article/details/123687820
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞