Thu*_*inh 1 c++ memory valgrind memory-leaks
您好,我通过 valgrind 运行了我的程序,这是报告
堆摘要:退出时使用:1 个块中的 8 个字节总堆使用情况:1 个分配,0 个释放,已分配 8 个字节泄漏摘要:肯定丢失:1 个块中的 8 个字节
这是我的程序
int main() {
NodeData nodedata1(1, 'a');
List list1;
list1.insert(&nodedata1);
return 0;
}
//---my List class
class List {
public:
List();
bool insert(NodeData*); // insert one Node into list
bool isEmpty() const;
private:
struct Node { // the node in a linked list
NodeData* data; // pointer to actual data, operations in NodeData
Node* next;
};
Node* head; // pointer to first node in list
};
// my bool insert method
bool List::insert(NodeData* rightPtr) {
Node* newPtr = new Node;
newPtr->data = rightPtr;
if (isEmpty() || *newPtr->data < *head->data) {
newPtr->next = head;
head = newPtr;
}
else {
Node* current = head;
while (current->next !=NULL && *current->next->data < *newPtr->data) {
current = current->next;
}
newPtr->next = current->next;
current->next = newPtr;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
Node您在方法中动态分配 ainsert并且从不删除它:
Node* newPtr = new Node;
Run Code Online (Sandbox Code Playgroud)
您需要跟踪这些Nodes并在析构函数中删除它们List,或者有一些其他安排来处理内存(即,将 的所有权传递Nodes给负责在适当的时候删除它们的东西)。