學習使用valgrind之記憶體檢測

來源:互聯網
上載者:User
C/C++中記憶體泄露常見的有3種:

1、malloc、realloc後忘記了free;new後忘記了delete;new []後忘記了delete[]。

2、採用使用計數的方式管理記憶體,兩個使用計數指標相互指向,導致記憶體泄露。

3、將分配且使用完的記憶體的放到了容器裡。

其中,第3中記憶體泄露方式在Java、C#等自動釋放記憶體的語言中也存在。

下面是第2種情況導致記憶體泄露的例子:

ValgrindMemcheck.cpp

#include <iostream>class A;class B;class A{public:    A()    :b(0),cnt(0)    {}    A(B *pB)    :b(pB),cnt(new int(1))    {}    A(const A &a)    :b(a.b),cnt(a.cnt)    {        ++*cnt;    }    A &operator =(const A &a);    ~A();private:    B *b;    int *cnt;};class B{public:    B()    :a(0),cnt(0)    {}    B(A *pA)    :a(pA),cnt(new int (1))    {}    B(const B &b)    :a(b.a),cnt(b.cnt)    {        ++*cnt;    }    B &operator =(const B &b);    ~B();private:    A *a;    int *cnt;};A &A::operator =(const A &a){    if(this == &a)        return *this;    if(cnt && 0 == --*cnt)    {        delete b;        delete cnt;    }    b = a.b;    cnt = a.cnt;    ++*cnt;    return *this;}A::~A(){    if(cnt && 0 == --*cnt)    {        delete b;        delete cnt;    }}B &B::operator =(const B &b){    if(this == &b)        return *this;    if(cnt && 0 == --*cnt)    {        delete a;        delete cnt;    }    a = b.a;    cnt = b.cnt;    ++*cnt;    return *this;}B::~B(){    if(cnt && 0 == --*cnt)    {        delete a;        delete cnt;    }}void test0(){    A a0;    B b0;    A a1(new B());    B b1(new A());}void test1(){    A *pA = new A();    B *pB = new B();    B b(pA);    A a(pB);}void test2(){    A a;    B b;    a = &b;    b = &a;}int main(void){    test0();    test1();    test2();    return 0;}

Makefile

all:ValgrindMemcheckValgrindMemcheck:ValgrindMemcheck.o        g++ -g -Wall -o $@ $^ValgrindMemcheck.o:ValgrindMemcheck.cpp        g++ -g -Wall -o $@ -c $<.PHONY:clean:        - $(RM) ValgrindMemcheck.cpp        - $(RM) ValgrindMemcheck.o

請問,test0、test1、test2中哪個有記憶體泄露呢?

運行:

valgrind --leak-check=full ./ValgrindMemcheck

就會發現test2中有記憶體問題。

參考文獻:

http://www.ibm.com/developerworks/cn/linux/l-cn-valgrind/

推薦幾個博文:

http://www.ibm.com/developerworks/cn/linux/l-cn-valgrind/

http://blog.dccmx.com/2011/01/valgrind-massif/

http://blog.dccmx.com/2011/01/callgrind/

http://blog.dccmx.com/2011/01/gprof/

http://blog.dccmx.com/2011/01/valgrind-memcheck/

http://eduunix.ccut.edu.cn/

http://www.oschina.net/project/tag/401/Neural-Network?lang=21&sort=view

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.