Linux 下查看内存泄露

Linux下 valgrind 检测内存泄露

  1. 编译时使用调试模式 -g
  2. 使用 valgrind 的 memcheck 工具来检测
valgrind --tool=memcheck --leak-check=full --log-file=./log.txt ./a.out

测试代码

#include 
using namespace std;
class Simple
{
public:
    Simple() {mIntPtr = new int();}
    virtual ~Simple() {delete mIntPtr;}
    void setIntPtr(int inInt) {*mIntPtr = inInt;}
private:
    int* mIntPtr;
};
void doSomething(Simple*& outSimplePtr)
{
    // 错误:指针原先所指对象内存未被释放,对象中mIntPtr所指内存未被释放
    outSimplePtr = new Simple();
}
int main()
{
    Simple* simplePtr = new Simple();
    doSomething(simplePtr);
    delete simplePtr;
    // 错误:重复释放指针
    delete simplePtr;
    return 0;
}

检测日志

log.txt
==3505== Memcheck, a memory error detector
==3505== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==3505== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==3505== Command: ./a.out
==3505== Parent PID: 27308
==3505==
==3505==
==3505== HEAP SUMMARY:
==3505== in use at exit: 20 bytes in 2 blocks
==3505== total heap usage: 4 allocs, 2 frees, 40 bytes allocated
==3505==
==3505== 20 (16 direct, 4 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==3505== at 0x4C285FC: operator new(unsigned long) (vg_replace_malloc.c:298)
==3505== by 0x400856: main (out_of_memory.cpp:21)
==3505==
==3505== LEAK SUMMARY:
==3505== definitely lost: 16 bytes in 1 blocks
==3505== indirectly lost: 4 bytes in 1 blocks
==3505== possibly lost: 0 bytes in 0 blocks
==3505== still reachable: 0 bytes in 0 blocks
==3505== suppressed: 0 bytes in 0 blocks
==3505==
==3505== For counts of detected and suppressed errors, rerun with: -v
==3505== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)

==11326== Invalid free() / delete / delete[] / realloc()
==11326== at 0x4C27016: operator delete(void*) (vg_replace_malloc.c:480)
==11326== by 0x4009D5: Simple::~Simple() (out_of_memory.cpp:8)
==11326== by 0x4008D5: main (out_of_memory.cpp:24)
==11326== Address 0x59630e0 is 0 bytes inside a block of size 16 free'd
==11326== at 0x4C27016: operator delete(void*) (vg_replace_malloc.c:480)
==11326== by 0x4009D5: Simple::~Simple() (out_of_memory.cpp:8)
==11326== by 0x4008B5: main (out_of_memory.cpp:23)

你可能感兴趣的:(Unix/Linux,C++,内存管理)