我正在学习链表,我认为规则是每个 new
都必须用 delete
来回答以清除动态分配的内存。这是我在列表中创建 3 个节点的代码,每次在 createNode
中使用 Node *temp = new Node;
创建一个 temp
节点> 功能。我的问题是,这不是在堆上动态分配吗,我是否需要 delete temp;
?没有它,我的代码运行良好,但是当我在函数末尾添加 delete temp;
时,我收到读取访问冲突错误。无论如何,它不应该有所作为吗,因为函数结束后 temp
现在不再被使用了?希望这是有道理的,感谢您的帮助。
#include <iostream>
#define Log(x) std::cout << x << std::endl;
struct Node
{
int data;
Node *next;
};
class SLList
{
private:
Node *head;
Node *tail;
public:
SLList()
{
head = NULL;
tail = NULL;
}
void createNode(int value)
{
Node *temp = new Node;
temp->data = value;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}
void printList()
{
Node *temp;
temp = head;
while (temp != NULL)
{
Log(temp->data);
temp = temp->next;
}
}
};
int main()
{
SLList list1;
list1.createNode(5);
list1.createNode(7);
list1.createNode(2);
list1.printList();
std::cin.get();
}
最佳答案
你确实应该释放动态分配的内存,但你试图在错误的时间这样做。
当您调用 Node *temp = new Node;
时,您不会创建临时节点,而是在堆上创建节点并在堆栈上创建指向它的临时指针。将该节点添加到列表后,您不再需要该指针(它的值存储在您的 SList 对象中),但您仍然需要它指向的对象。
所以:
- 是的,你应该通过调用 delete 来释放你的内存
- 不,您不能在
createNode
方法中执行此操作,因为您仍然需要此数据。在不需要时释放内存:从列表中删除元素时。
关于C++ SLList - 从堆中删除临时节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53198483/