gpt4 book ai didi

c++ - valgrind 在单链接列表示例中显示内存泄漏

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:24 26 4
gpt4 key购买 nike

Here is my code.

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
int data;
Node* next;
};

void printList(Node* n)
{
while (n != NULL) {
cout << n->data << " ";
n = n->next;
}
}

void delete_list(Node *n)
{
Node *tmp = NULL;
tmp = new Node();
while (n != NULL){
tmp=n->next;
delete (Node *)n;
n=tmp;
}
delete (Node *)tmp;
}


int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;

head = new Node();
second = new Node();
third = new Node();

head->data = 1;
head->next = second;

second->data = 2;
second->next = third;

third->data = 3;
third->next = NULL;

printList(head);

// Delete the entire list
delete_list(head);

return 0;
}
  • 堆摘要:在此处输入代码 在导出处使用:1 个 block 中的 16 个字节 堆总使用量:6 次分配,5 次释放,分配了 73,792 字节 1个 block 中的16个字节肯定丢失在丢失记录1 of 1中 在 0x4C3017F:operator new(unsigned long)(在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so 中) 通过 0x10895E: delete_list(Node*) (demo.cpp:24) 通过 0x108A87: main (demo.cpp:58) 泄漏总结: 绝对丢失:1 个 block 中的 16 个字节 间接丢失:0 个 block 中的 0 个字节 可能丢失:0 个 block 中的 0 个字节 仍然可达:0 个 block 中的 0 个字节 抑制:0 个 block 中的 0 个字节 对于检测到的和抑制的错误的计数,重新运行:-v 错误摘要:1 个上下文中的 1 个错误(抑制:0 个中的 0 个)

最佳答案

void delete_list(Node *n)
{
Node *tmp = NULL;

// this is your memory leak:
// you just created a new node ...
tmp = new Node();

while (n != NULL)
{
// ... and very first thing you do is assigning another node to the only
// pointer holding the node created just before
tmp = n->next;

delete (Node *)n;
n = tmp;
}

// apart from cast being obsolete (tmp HAS appropriate type!)
// tmp is already nullptr and you don't delete anything at all
delete (Node *)tmp;
}

这个例子很好地展示了为什么尽可能保持局部变量是个好主意:

while (n != NULL)
{
Node* tmp = n->next;
delete (Node *)n;
n = tmp;
}

你根本无法在不需要的情况下分配任何东西(甚至创建不相关的对象)或试图删除不再存在的东西......

关于c++ - valgrind 在单链接列表示例中显示内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59465903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com