私はC++とvalgrindを学ぼうとしています。だから私はそれをテストするために次のコードを書いた。しかし、私はいくつかのメモリリークを取得します。誰でもメモリリークの原因を説明できますか?前もって感謝します。 valgrindのベクトルポインタ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)
から
#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;
}
は、私は、ポインタのコピーから削除することは許されないか、私は間違って何かをやっているのですか?
フォーラムでは、多くの「ベクトル」が表示されているため、私は泣きたいと思っています。 –
あなたの答えをありがとう。本当に私のような初心者のために役立ちます。しかし、外部関数のためにポインターを渡す必要がある場合はどうなりますか?ポインタのベクトル/配列を使用するのは大丈夫でしょうか、それともあなたが推奨するより良い解決策がありますか? –
@oliten:アドレス演算子 '&' :-)を使用できます。 –