关于内存泄漏 - 新
regarding memory leak - new
我正在学习一些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() 调用都会分配一个新节点,因此如果您要添加适当的清理代码,则需要遍历链表并删除列表中的每个节点。 由于一个节点只持有指向另一个节点的指针,因此它没有关于谁拥有该节点的信息,也不会自动删除它。
出于这个原因,您通常希望创建一个实际的"列表"结构来管理分配,然后销毁其析构函数中的节点。
相关文章:
- C++功能泄漏内存,我是C++新手,不确定如何解决
- 我的堆栈弹出式磁带的实现是否泄漏内存?
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 析构函数 C++ 使泄漏内存
- 构造函数对象赋值是否泄漏内存
- corba :: orb_init泄漏内存
- Gmock泄漏内存
- 如何在不泄漏内存的情况下删除链接列表
- Visual C ODBC关闭记录集泄漏内存
- 为什么泄漏内存比在动态数组上执行 delete[] 慢
- OpenGL正在泄漏内存.哪个对象未释放
- 可以std ::退出泄漏内存
- uiautomation findall泄漏内存
- 为什么在此OpenCL代码中泄漏内存,为什么要泄漏内存
- pthread在完成后会泄漏内存
- win32 标准::线程泄漏内存
- 返回指向同一变量的指针是否会泄漏内存
- 使用clectType(new any_type())可能会泄漏内存泄漏
- Windows开发:如何确定我的应用程序是否正在泄漏内存
- WinHttp打开泄漏内存