gpt4 book ai didi

C++内存泄漏形式将数据插入链表

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:40 27 4
gpt4 key购买 nike

我需要为我的链接列表使用 unique_ptr 或 shared_ptr,但我仍然遇到内存泄漏。对于这种情况,我将所有成员数据保留为 public。第一次插入链表不会导致任何内存泄漏,但随着 for 循环的继续,每次我将一个对象作为数据插入链表时,调试器会显示更多的内存泄漏。我不知道是什么导致了如此多的内存泄漏。会不会是某些共享点引起的?

    template <typename T>
class Node
{
public:
T data;
shared_ptr<Node<T>> next;
shared_ptr<Node<T>> prev;

public:
Node() { next = NULL; prev = NULL; data = 0; }
Node(T value) { next = NULL; prev = NULL; data = value; }
T getData() { return data; }

};

template <typename T>
class DoubleLinkedList
{
public:
shared_ptr<Node<T>> head;
shared_ptr<Node<T>> tail;
public:
DoubleLinkedList()
{
head = NULL;
tail = NULL;
total = 100;
for (int i = 0; i < total; i++)
{
Insert(objectgetsinsertedhere);
}
}


void Insert(T data)
{
shared_ptr<Node<T>> rover = NULL;
T value(data);
if (head == NULL)
{
head = make_shared<Node<T>>(data);
tail = head;
}
else
{
shared_ptr<Node<T>> nu = make_shared<Node<T>>(data);
nu->prev = tail;
if (head == tail)
head->next = nu;
tail->next = nu;
tail = nu;
}
}
};

编辑:这是调试器显示为内存泄漏的一部分。

Detected memory leaks!
Dumping objects ->
{211} normal block at 0x005CF798, 8 bytes long.
Data: <x \ > 78 98 5C 00 00 00 00 00
{210} normal block at 0x005CF258, 8 bytes long.
Data: <\ \ > 5C 98 5C 00 00 00 00 00
{209} normal block at 0x005CF1B0, 8 bytes long.
Data: <@ \ > 40 98 5C 00 00 00 00 00
{205} normal block at 0x005C9830, 136 bytes long.
Data: <H > 48 A9 0C 00 01 00 00 00 01 00 00 00 CD CD CD CD
{191} normal block at 0x005CF3A8, 8 bytes long.
Data: < \ > A8 DB 5C 00 00 00 00 00
{190} normal block at 0x005CF0D0, 8 bytes long.
Data: < \ > 8C DB 5C 00 00 00 00 00
{189} normal block at 0x005CF060, 8 bytes long.
Data: <p \ > 70 DB 5C 00 00 00 00 00
{185} normal block at 0x005CDB60, 136 bytes long.
Data: <H > 48 A9 0C 00 01 00 00 00 01 00 00 00 CD CD CD CD
Object dump complete.

最佳答案

问题是您的共享指针中有一个所有权循环。这使得内存不会自动释放,因为总是至少有一个所有者,即使链表本身已被销毁。解决这个问题的一种方法是只对 next 指针使用共享指针,而不是 prev 指针:

template <typename T>
class Node
{
public:
T data;
shared_ptr<Node<T>> next;
Node<T> *prev;

public:
Node() { next = NULL; prev = NULL; data = 0; }
Node(T value) { next = NULL; prev = NULL; data = value; }
T getData() { return data; }

};

这会阻止所有权循环。列表拥有头部,头部拥有第二个元素,等等。当列表被销毁时,头部没有所有者,所以头部被破坏,现在第二个元素没有所有者,所以它得到销毁等

关于C++内存泄漏形式将数据插入链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36681735/

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