英文:
valgrind LEAK SUMMARY: definitely lost
问题
Memory leak is happening in the Data::getX()
method. The memory allocated for the Data
object in this method is not being freed before returning. To fix the memory leak, you should delete the Data
object before returning it. Here's the corrected version of the Data::getX()
method:
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);
// Free the memory before returning
for(int i = 0; i < r; i++){
delete[] this->data[i];
}
delete[] this->data;
return data;
}
In this corrected version, the memory allocated for this->data
is properly freed before creating the new Data
object. This should resolve the memory leak issue.
英文:
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?
答案1
得分: 1
在析构函数中,我忘记释放指针 this->data。所以,当我添加
delete[] this->data;
this->data = nullptr;
问题已经解决。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论