gpt4 book ai didi

c++ - vector 指针导致 valgrind 内存泄漏

转载 作者:行者123 更新时间:2023-11-30 03:03:31 25 4
gpt4 key购买 nike

我正在尝试学习 C++ 和 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)

我是否不允许从指针的拷贝中删除,还是我做错了什么?

最佳答案

你永远不会在 a 上调用 delete

当然,这里重要的一点是您正在使用指针的 vector。你到底为什么要这样做?让 vector 为您管理内存!

关于c++ - vector 指针导致 valgrind 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9320322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com