为什么valgrind显示泄漏,即使释放包含动态分配对象的向量?

时间:2014-07-04 12:03:45

标签: c++ linux vector valgrind

我使用new:

在堆上分配了一个向量
std::vector<t*> *vec = new std::vector<t*>;

此向量包含类“t”的类对象,这些类对象使用新的

创建
t *ptr1 = new t();
t *ptr2 = new t();
t *ptr3 = new t();
t *ptr4 = new t();

现在当我删除矢量时,预计添加到它的所有这些对象也应该被销毁,我的意思是:

std::vector<t*> *vec = new std::vector<t*>;
 vec->push_back(ptr1);
 vec->push_back(ptr2);
 vec->push_back(ptr3);
 vec->push_back(ptr4);
ptr1指向的内存,ptr2,ptr3,ptr4也应该被释放。

但Valgrind将此视为泄漏!!! Valgrind有问题吗?

==15634==
==15634== HEAP SUMMARY:
==15634==     in use at exit: 48 bytes in 8 blocks
==15634==   total heap usage: 12 allocs, 4 frees, 128 bytes allocated
==15634==
==15634== LEAK SUMMARY:
==15634==    definitely lost: 32 bytes in 4 blocks
==15634==    indirectly lost: 16 bytes in 4 blocks
==15634==      possibly lost: 0 bytes in 0 blocks
==15634==    still reachable: 0 bytes in 0 blocks
==15634==         suppressed: 0 bytes in 0 blocks
==15634== Rerun with --leak-check=full to see details of leaked memory
==15634==
==15634== For counts of detected and suppressed errors, rerun with: -v
==15634== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

以下是供大家参考的完整程序:

#include <iostream>
#include <vector>
using namespace std;

class t
{
int *ptr;
public:
  t()
  {
    cout << "t's constructor" << endl;
    ptr = new int(50);
  }
 ~t()
  {
    cout << "t's destructor called" << endl;
    delete ptr;
  }

  void func()
  {
     cout << "This is class t's function" << endl;
  }

};

//void func(int *ptr, t* ptr1)
void func(t* ptr1)
{
 //delete ptr;
 delete ptr1;
}

int main( )
{
 //int *ptr;

 t *ptr1 = new t();
 t *ptr2 = new t();
 t *ptr3 = new t();
 t *ptr4 = new t();
 //ptr =new int(20);
 //func(ptr, ptr1);
 //func(ptr1);

 std::vector<t*> *vec = new std::vector<t*>;
 vec->push_back(ptr1);
 vec->push_back(ptr2);
 vec->push_back(ptr3);
 vec->push_back(ptr4);

 delete vec;
 //delete ptr1; ===============> Are these required? Shouldn't delete vec take care?
// delete ptr2;
 //delete ptr3;
 //delete ptr4;

}

2 个答案:

答案 0 :(得分:18)

  

现在当我删除矢量时,预计添加到它的所有这些对象都应该被销毁

他们是。你添加了指针,指针将被销毁。

但是,这并没有说明指针指向的东西。简而言之,你的假设是错误的。

您的选择:

  • delete每个指针对象在销毁向量之前
  • 使用智能指针
  • 停止使用指针!停止使用动态分配!
    std::vector<t>在大多数情况下应该没问题。

答案 1 :(得分:1)

当verctor被销毁时,它只销毁了向量分配的内存。这意味着,verctor需要内部结构来保持您插入的t *。 desctor析构函数确定地删除了该内存。但是,“新建”的值不会被矢量释放。

您是删除这些记忆的负责人。