泄密者:发现错误!内存未被释放
LEAKER: errors found! memory was not deallocated
我不断收到同样的错误:
泄密者:发现错误!
发现泄漏:2 个分配(48 字节)。
unknown:unknown():0 内存泄漏:内存未被释放。
unknown:unknown():0 内存泄漏:内存未被释放。
我一直在检查我的析构函数和我的 Clear() 函数,但我不知道我遗漏了什么。我知道我应该删除一些东西,但我不知道我应该删除什么。当我尝试删除 head 或 tail 时,我收到一条错误消息,指出从未分配指针。请帮忙!
您没有包含 main
。您发布的只是一个 class 定义,它本身不会泄漏。但是,很容易想出一个泄漏的例子:
int main() {
LinkedList<int> l;
}
因为你有 class 个初始值设定项:
private:
Node* head = new Node; // Node pointer for the head
Node* tail = new Node; // Node pointer for the tail
unsigned int count; // counting nodes in list
};
然后默认构造函数丢弃指向已分配 Node
的指针并分配 nullptr
:
template <typename T>
LinkedList<T>::LinkedList()
{
// Default Constructor
count = 0;
head = nullptr;
tail = nullptr;
}
成员在构造函数主体运行之前初始化,一旦构造函数主体运行,您将丢失对分配的 head
和 tail
.
的任何引用
需要消化的内容很多,但您可能至少有一个错误来源
class LinkedList
{
...
private:
Node* head = new Node; // Node pointer for the head
Node* tail = new Node; // Node pointer for the tail
unsigned int count;
}
然后在你的构造函数中
LinkedList<T>::LinkedList()
{
// Default Constructor
count = 0;
head = nullptr;
tail = nullptr;
}
因此您导致默认初始化程序调用 new
,它正在执行堆分配。然后在构造函数 body 中,用 nullptr
覆盖这些指针!这立即是泄漏,您现在没有对那些 heap-allocated objects 的引用,并且无法释放内存。
我在这里尝试的第一件事就是将您的 header 代码更改为
class LinkedList
{
...
private:
Node* head = nullptr; // Node pointer for the head
Node* tail = nullptr; // Node pointer for the tail
unsigned int count = 0;
}
然后重构您的构造函数(它们不再需要将指针设置为 nullptr
或将您的 count
设置为 0
)。更好的是,对于您的默认构造函数,您可以将其声明为
// Default Constructor
LinkedList() = default;
我不断收到同样的错误:
泄密者:发现错误! 发现泄漏:2 个分配(48 字节)。 unknown:unknown():0 内存泄漏:内存未被释放。 unknown:unknown():0 内存泄漏:内存未被释放。
我一直在检查我的析构函数和我的 Clear() 函数,但我不知道我遗漏了什么。我知道我应该删除一些东西,但我不知道我应该删除什么。当我尝试删除 head 或 tail 时,我收到一条错误消息,指出从未分配指针。请帮忙!
您没有包含 main
。您发布的只是一个 class 定义,它本身不会泄漏。但是,很容易想出一个泄漏的例子:
int main() {
LinkedList<int> l;
}
因为你有 class 个初始值设定项:
private: Node* head = new Node; // Node pointer for the head Node* tail = new Node; // Node pointer for the tail unsigned int count; // counting nodes in list };
然后默认构造函数丢弃指向已分配 Node
的指针并分配 nullptr
:
template <typename T> LinkedList<T>::LinkedList() { // Default Constructor count = 0; head = nullptr; tail = nullptr; }
成员在构造函数主体运行之前初始化,一旦构造函数主体运行,您将丢失对分配的 head
和 tail
.
需要消化的内容很多,但您可能至少有一个错误来源
class LinkedList
{
...
private:
Node* head = new Node; // Node pointer for the head
Node* tail = new Node; // Node pointer for the tail
unsigned int count;
}
然后在你的构造函数中
LinkedList<T>::LinkedList()
{
// Default Constructor
count = 0;
head = nullptr;
tail = nullptr;
}
因此您导致默认初始化程序调用 new
,它正在执行堆分配。然后在构造函数 body 中,用 nullptr
覆盖这些指针!这立即是泄漏,您现在没有对那些 heap-allocated objects 的引用,并且无法释放内存。
我在这里尝试的第一件事就是将您的 header 代码更改为
class LinkedList
{
...
private:
Node* head = nullptr; // Node pointer for the head
Node* tail = nullptr; // Node pointer for the tail
unsigned int count = 0;
}
然后重构您的构造函数(它们不再需要将指针设置为 nullptr
或将您的 count
设置为 0
)。更好的是,对于您的默认构造函数,您可以将其声明为
// Default Constructor
LinkedList() = default;