I write a class 'Data' as following.
//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;
}
It can compile and run normally. Then when I scan the code with valgrind, it prompts that the code has a memory leak.
==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()
Where is the memory leak problem in this code? Thank you! Here is my code in 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;
Where is the memory leak problem in this code?
In the destructor, I forgot to release the pointer this->data. So, when I add
delete[] this->data;
this->data = nullptr;
it has been fixed.