2012-02-16 64 views
1

我正在嘗試學習C++和valgrind。所以我寫了下面的代碼來測試它。但我得到了一些內存泄漏。任何人都可以解釋什麼是造成內存泄漏?提前致謝。矢量指針導致valgrind內存泄漏

#include <vector> 
#include <iostream> 
using namespace std; 

class test 
{ 
    int c; 
     public: 
     void whatever(); 
}; 
void test:: whatever() 
{ 
    vector<test*> a; 
    if(true) 
    { 
      test* b = new test(); 
      b->c = 1; 
      a.push_back(b); 
    } 
    test* d = a.back(); 
    cout << "prints: " << d->c; 
    delete d; 
} 

int main() 
{ 
    test* a = new test(); 
    a->whatever(); 
    return 1; 
} 

從Valgrind的

==28548== HEAP SUMMARY: 
==28548==  in use at exit: 4 bytes in 1 blocks 
==28548== total heap usage: 3 allocs, 2 frees, 16 bytes allocated 
==28548== 
==28548== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 
==28548== at 0x4C27CC1: operator new(unsigned long) (vg_replace_malloc.c:261) 
==28548== by 0x400C36: main (in a.out) 
==28548== 
==28548== LEAK SUMMARY: 
==28548== definitely lost: 4 bytes in 1 blocks 
==28548== indirectly lost: 0 bytes in 0 blocks 
==28548==  possibly lost: 0 bytes in 0 blocks 
==28548== still reachable: 0 bytes in 0 blocks 
==28548==   suppressed: 0 bytes in 0 blocks 
==28548== 
==28548== For counts of detected and suppressed errors, rerun with: -v 
==28548== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4) 

不允許我從一個指針的拷貝,刪除或我在做別的事情了?

回答

2

你從來沒有a調用delete

當然,這裏最重要的一點是,你正在使用指針的vector。你爲什麼會這樣做?讓矢量照顧你的內存管理!

1

您在main()末忘了delete a;

注意一切你寫的應該從未進入真正的代碼。除非您絕對必須知道原因,否則絕對不應該使用動態分配(new)。


假設你希望爲教育目的指針的載體,那麼這裏寫它的一個更好的辦法:

#include <vector> 
#include <memory> // for unique_ptr 

// intentionally left blank; NO abusing namespace std! 

struct Foo 
{ 
    int c; 

    void whatever() 
    { 
     std::vector<std::unique_ptr<test>> v; 

     if (true) 
     { 
      v.emplace_back(new test); 
      v.back()->c = 1; 
     } 

     // everything is cleaned up automagically 
    } 
}; 

int main() 
{ 
    Test a;  // automatic, not dynamic 
    a.whatever(); 

    return 1; 
} 

這仍然只是爲教育目的;在現實生活中,你會盡力用普通的std::vector<test>來做,因爲vector已經是一個動態數據結構,並且很少需要額外的間接級別。

+2

我看到這麼多'矢量'在論壇,這讓我想哭... – 2012-02-16 22:53:13

+0

謝謝您的回答。對於像我這樣的初學者真的很有幫助。但是如果由於外部函數需要傳遞指針,會發生什麼?使用向量/指針數組可以嗎?還是有更好的解決方案? – 2012-02-17 00:43:29

+0

@oliten:你可以使用操作符'&':-) – 2012-02-17 06:05:20

0

內存泄漏是在主。您不刪除分配的test對象。