[英]C++ - Freeing memory allocated in main but pointed to in a seperate class
[英]C++- freeing dyncamically allocated memory for a member variable of a class gives error
我有这样的课:
Class Attributes
{
Public:
float* data;
float* x;
float min_x;
float max_x;
~Attributes();
};
在主函数的某个时候,我创建了这个:
Attributes attr;
float* data =(float*)malloc(N*sizeof(float));
float* x =(float*)malloc(N*sizeof(float));
/* populate values of data and x */
attr.data = data;
attr.x = x;
然后,填充值并进行操作。
现在我了解到,由于仅在堆栈上创建对象,因此无需删除它。 但是我认为它会自动删除仅包含类内部成员在内的成员变量,但是我必须显式free
为使用malloc
用于data
和x
分配的内存
所以我写了Class的析构函数为
Attributes::~Attributes()
{
if(data!=NULL)
free(data);
if(x!=NULL)
free(x);
}
正如预期的那样,一旦attr
的范围过期,就会调用析构函数。 但是在free
执行时会出现以下错误:
*** Error in '~/Plot':double free or corruption (!prev): 0x0000000002a7e9d0 ***
谁能解释我在做什么错?
您可能正在某个地方复制attr
。
这是您问题的(正在解决,未解决其他人在评论中提到的问题)版本。 它不会触发任何doublefree错误:
#include <cstdlib>
class Attributes
{
public:
float* data;
float* x;
float min_x;
float max_x;
~Attributes() {
if(data!=NULL)
free(data);
if(x!=NULL)
free(x);
}
};
int main(int argc, char** argv) {
int N = 100;
Attributes attr;
float* data =(float*)malloc(N*sizeof(float));
float* x =(float*)malloc(N*sizeof(float));
attr.data = data;
attr.x = x;
}
关键是:复制attr(甚至隐式)时,您有责任对
您可以使用智能指针库来解决您的特定问题。
只需使用std::vector
,就像这样:
class Attributes
{
public:
void resize(std::size_t size)
{
data.resize(size);
x.resize(x);
}
private:
std::vector<float> data;
std::vector<float> x;
float min_x;
float max_x;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.