我正在嘗試學習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)
不允許我從一個指針的拷貝,刪除或我在做別的事情了?
我看到這麼多'矢量'在論壇,這讓我想哭... –
2012-02-16 22:53:13
謝謝您的回答。對於像我這樣的初學者真的很有幫助。但是如果由於外部函數需要傳遞指針,會發生什麼?使用向量/指針數組可以嗎?還是有更好的解決方案? – 2012-02-17 00:43:29
@oliten:你可以使用操作符'&':-) – 2012-02-17 06:05:20