Linux 下查看内存泄露

13 篇文章 0 订阅
1 篇文章 0 订阅

Linux下 valgrind 检测内存泄露

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

测试代码

#include <iostream>
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)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值