矢量指针导致valgrind内存泄漏

时间:2012-02-16 22:49:05

标签: c++ valgrind

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

我是否不允许从指针的副本中删除或者我做错了什么?

3 个答案:

答案 0 :(得分:2)

您永远不会在delete上致电a

当然,这里重要的一点是你使用的是vector指针。为什么你会这样做呢?让vector为你处理内存管理!

答案 1 :(得分:1)

您忘了在delete a;结束时main()

请注意,您编写的所有内容都应该从不进入实际代码。你绝不应该使用动态分配(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 :(得分:0)

内存泄漏主要是。您没有删除已分配的test对象。