繁体   English   中英

C ++-释放为类的成员变量动态分配的内存会产生错误

[英]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用于datax分配的内存

所以我写了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(甚至隐式)时,您有责任对

  • 跟踪资源使用情况(两个对象引用相同的内存)
  • 或复制已分配的资源(即,根据您的特定语义,您可以在(copy-)构造函数中将指针设置为NULL,或者在构造时分配一个新数组(这意味着您还需要认真携带length字段) ,您应该使用std :: vector)

您可以使用智能指针库来解决您的特定问题。

只需使用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.

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