我正在学习一些c ++,并有一个简单的关于内存泄漏的问题。用新的创建的所有内容也应该删除,对吗?
因此,例如,此代码应该有内存泄漏:
#include <iostream>
struct Node
{
int data;
Node* next;
};
bool insert(Node** head, int val)
{
Node* temp = *head;
if((*head)->data == val)
return false;
if(*head == nullptr || (*head)->data > val)
{
Node* new_node = new Node();
new_node->next = *head;
new_node->data = val;
*head = new_node;
return true;
}
while(temp->next != nullptr && temp->next->data <= val)
{
temp = temp->next;
if(temp->data == val)
return false;
}
//Sätt in ny nod
Node* new_node = new Node{val, temp->next};
temp->next = new_node;
return true;
}
void print(Node** head)
{
Node* temp = *head;
while(temp != nullptr)
{
std::cout << temp->data << ' ';
temp = temp->next;
}
}
int main()
{
Node* head = new Node{0, nullptr};
Node* another = new Node{1, nullptr};
head->next = another;
for(unsigned i = 0; i != 10; ++i)
if(insert(&head, i % 5))
std::cout << "Inserted " << i % 5 << " into the list.n";
else
std::cout << "Could not insert " << i % 5 << " into the list.n";
std::cout << "List is: ";
print(&head);
insert(&head, -1);
insert(&head, 22);
insert(&head, 13);
insert(&head, 11);
insert(&head, 19);
std::cout << "nList is: ";
print(&head);
return 0;
}
我正在尝试了解内存泄漏,所以我必须遍历结构并删除所有内容,还是只删除"head"和"另一个"就足够了,以防止此代码出现内存泄漏。
提前致谢
不,删除"头"和"另一个"是不够的。 在此代码中,每个 insert() 调用都会分配一个新节点,因此如果您要添加适当的清理代码,则需要遍历链表并删除列表中的每个节点。 由于一个节点只持有指向另一个节点的指针,因此它没有关于谁拥有该节点的信息,也不会自动删除它。
出于这个原因,您通常希望创建一个实际的"列表"结构来管理分配,然后销毁其析构函数中的节点。