저는 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 : 주소 연산자'&'를 사용할 수 있습니다 : –