[英]Valgrind reports memory leak but I don't understand where it occurs
我已經寫了一個前向鏈接列表,但是當我通過valgrind運行它時,它在我的remove(const int函數)中報告了內存泄漏,我還不太清楚為什么。
這是valgrind抱怨的刪除功能。 該函數位於文件“ list.cc”中。
void Plist::remove(const int pos)
{
current_index = root;
if( pos == 0 )
{
delete root;
root = current_index -> pointer;
}
else
{
for(int n = 0; n<pos-1; ++n)
{
current_index = current_index -> pointer;
}
index * new_link = current_index -> pointer -> pointer;
delete current_index -> pointer;
current_index -> pointer = new_link;
}
}
這是屬於“ list.cc”的頭文件“ list.h”。
class Plist
{
private:
class index
{
public:
index(int value, index * ptr);
index(int value);
int val{0};
index * pointer{nullptr};
};
index * root = nullptr;
index * current_index = nullptr;
public:
Plist(){}
~Plist();
Plist (Plist& lst);
Plist& operator=(Plist& lst);
void insert(const int val);
void remove(const int pos);
void print();
};
任何幫助表示贊賞!
這不是您的錯誤,但是以下代碼不正確:
current_index = root;
if( pos == 0 )
{
delete root;
root = current_index -> pointer;
}
由於current_index = root
,因此delete root
意味着current_index
現在指向已銷毀的對象,您可以在下一行中取消引用。 哎呀。
不是您詢問的問題,但是此代碼不起作用:
current_index = root;
if( pos == 0 )
{
delete root;
root = current_index -> pointer;
}
之后delete root
對象通過指向root
或副本root
,例如, current_index
,都死了。 您需要遵循以下原則:
current_index = root;
if (pos == 0) {
current_index = current_index->pointer;
delete root;
root = current_index;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.