【发布时间】:2016-01-31 12:01:10
【问题描述】:
对于我的一个编程课程的作业,我们必须创建一个邻接表,它是一个看起来像这样的链表的链表。
A->B->C
↓
B->A->D
↓
C->D
↓
D->A->B->C
我在尝试释放析构函数中分配的内存时遇到内存泄漏问题。我已经尝试了一段时间,但还没有找到/想出任何可行的解决方案。
另外,请忽略头文件中包含的实现。我们被告知可以完成这项任务。
Valgrind 错误消息:
==2316== 堆摘要:
==2316== 在退出时使用:2 个块中的 48 个字节
==2316== 总堆使用量:3 个分配,1 个释放,64 个字节分配
==2316==
==2316== 1 个块中的 48 个(32 个直接,16 个间接)字节在 2 个丢失记录 2 中肯定丢失
==2316== at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2316== by 0x4012EE: main (main.cpp:34)
==2316==
==2316== 泄漏摘要:
==2316== 肯定丢失:1 个块中的 32 个字节
==2316== 间接丢失:1 个块中的 16 个字节
==2316== 可能丢失:0 个块中的 0 个字节
==2316== 仍然可以访问:0 个块中的 0 个字节
==2316== 抑制:0 个块中的 0 个字节
==2316==
==2316== 对于检测到和抑制的错误计数,重新运行:-v
==2316== 错误摘要:来自 1 个上下文的 1 个错误(已抑制:来自 0 的 0 个)
这是我正在使用的一些代码(使用 gcc c++11 编译):
链接列表.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
template<typename T> struct Node
{
T data;
Node<T>* next;
};
template<typename T> class LinkedList
{
private:
Node<T>* head;
Node<T>* tail;
Node<T>* curr;
unsigned int size;
void insertAtHead(T val)
{
Node<T>* temp = new Node<T>;
temp->data = val;
temp->next = nullptr;
head = temp;
tail = temp;
curr = temp;
size++;
}
public:
LinkedList()
{
head = nullptr;
tail = nullptr;
curr = nullptr;
size = 0;
}
~LinkedList()
{
Node<T>* nodePtr = head;
Node<T>* temp;
while (nodePtr != nullptr)
{
temp = nodePtr;
nodePtr = nodePtr->next;
delete temp;
}
size = 0;
}
void insertAtTail(T val)
{
if (head == nullptr)
insertAtHead(val);
else
{
Node<T>* temp = new Node<T>;
temp->data = val;
curr->next = temp;
temp->next = nullptr;
tail = temp;
curr = temp;
size++;
}
}
// returns the value at the node location passed if it exists within the
// linked list, otherwise nothing is returned
T get(int location)
{
// std::cout << "size: " << size << std::endl;
if (location >= 0 && location <= size)
{
Node<T>* temp = head;
unsigned int counter = 0;
while (counter != location)
{
temp = temp->next;
counter++;
}
return temp->data;
}
}
};
#endif // LINKEDLIST_H
main.cpp
#include "linkedlist.h"
int main()
{
LinkedList<LinkedList<int>*> matrix;
matrix.insertAtTail(new LinkedList<int>);
matrix.get(0)->insertAtTail(6);
return 0;
}
【问题讨论】:
-
并非
get(location)的所有路径都返回值。使用编译器的警告来查找此类问题(例如-Wall -Wextra -pedantic) -
你在堆上声明了一个
LinkedList<int>并且永远不会删除它。我错过了什么?
标签: c++ c++11 memory-management memory-leaks destructor