简体   繁体   English

如何在C ++中删除指向指针的指针的内存

[英]How to delete memory of a pointer to pointer in C++

Using Valgrind, I see that I have a problem while deleting the memory in the following function:使用 Valgrind,我发现在以下函数中删除内存时出现问题:

Obj1 Obj1::operator*(const Obj1& param) const {
int n = param.GetSize(2);
Obj2** s = new Obj2*[n];
for( int i = 0; i < n; ++i) {
    s[i] = new Obj2(*this*param.GetColumn(i+1));
}
Obj1 res = foo(s,n);
for(int i=n-1;i>-1;i--) {
    s[i]->~Obj2();
}
delete[] s;
return res;

Valgrind tells me that the leak comes from the line Valgrind 告诉我泄漏来自线路

s[i] = new Obj2(*this*param.GetColumn(i+1));

I'm not pretty sure if the problem is when I try to free the memory.我不太确定问题是否出在我尝试释放内存时。 Can anyone tell me how to fix this problem?谁能告诉我如何解决这个问题?

Here:这里:

 s[i] = new Obj2(*this*param.GetColumn(i+1));

you create a dynamic object and assign s[i] to point to it.您创建一个动态对象并分配s[i]指向它。

In order to delete it, you do this:要删除它,请执行以下操作:

delete s[i];

Unless you do that, the allocation will leak.除非您这样做,否则分配将泄漏。

You must repeat that in a loop for every i just like you repeated the allocations.您必须在循环中为每个i重复此操作,就像您重复分配一样。 You of course have to do this before you delete s itself.您当然必须在删除s之前执行此操作。


 s[i]->~Obj2();

Don't do that.不要那样做。 Calling the destructor is not appropriate here.在这里调用析构函数是不合适的。 delete will call the destructor. delete将调用析构函数。


PS Don't use raw owning pointers. PS 不要使用原始拥有指针。 Use containers or smart pointers instead.改用容器或智能指针。 std::vector is a standard containers for dynamic arrays. std::vector是动态数组的标准容器。

PPS You should avoid unnecessary dynamic allocation. PPS 你应该避免不必要的动态分配。 Your example doesn't demonstrate any need to allocate the pointed objects dynamically.您的示例没有说明任何需要动态分配指向的对象。 So, in this case you should probably use std::vector<Obj2> .因此,在这种情况下,您可能应该使用std::vector<Obj2>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM