valgrind 泄漏摘要:绝对丢失

问题描述 投票:0回答:1

我写了一个类“数据”如下。

//code in .h file
class Data{
private:
    int col = 0;
    int row = 0;
    float **data = NULL;
public:
    //Constructor
    Data();
    Data(int r, int c);
    Data(int r, int c, float **data1);
    Data* getX();
};

//code in .cpp file
Data::~Data(){
    for(int i = 0; i < this->row; i++){
        delete[] this->data[i];
        this->data[i] = nullptr;
    }
    this->row = 0;
    this->col = 0;
}

Data::Data(){
    this->col = 0;
    this->row = 0; 
    this->data = nullptr; 
}


Data::Data(int r, int c,float **data1){
    this->row = r;
    this->col = c;
    this->data = new float*[r];
    for (int i = 0; i < r; i++){
        this->data[i] = new float[c];
        memcpy(this->data[i],data1[i],sizeof(float)*c);
    }
}
Data* Data::getX(){
    if(this->col <= 0) throw missing_data();
    int r = this->row;
    int c = this->col - 1;
    Data *data = new Data(r,c,this->data);
    return data;
}

可以正常编译运行。然后我用valgrind扫描代码的时候提示代码有内存泄漏

==1247551== 400 bytes in 5 blocks are definitely lost in loss record 181 of 182
==1247551==    at 0x483E217: operator new[](unsigned long) (vg_replace_malloc.c:640)
==1247551==    by 0x11C074: Data::Data(int, int, float**) 
==1247551==    by 0x11C707: Data::getX() 

这段代码的内存泄漏问题在哪里? 谢谢你! 这是我在 main() 中的代码。

    Data *X = this->data->getX();
    GHInfoAF<float> GandH = Divide::APdividebinning(set,ghinfo,X,sbtp->getMaxBining(),tempqpoint);
    G_H.push_back(GandH); 
    delete X;
    X = nullptr; 

这段代码的内存泄漏问题在哪里?

valgrind
1个回答
1
投票

在析构函数中,忘记释放指针this->data。 所以,当我添加

delete[] this->data; 
this->data = nullptr;

已修复

© www.soinside.com 2019 - 2024. All rights reserved.