gpt4 book ai didi

c++ - 为什么将项目添加到链表会导致段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:56 24 4
gpt4 key购买 nike

当 numberOfItems 设置为 10000 时,它起作用。当 numberOfItems 设置为 90000 时,会导致段错误。

#include <iostream>
#include <memory>

template<typename T> class Queue {
public:
struct Node {
std::shared_ptr<T> Data;
std::unique_ptr<Node> Next;
};

Queue() : mHead{new Node}, mTail{mHead.get()} {}

Void push(T dataValue) {
mTail->Data = std::make_shared<T>(std::move(dataValue));
mTail->Next.reset(new Node);
mTail = mTail->Next.get();
}

bool empty() { return mHead.get()==mTail;}

std::unique_ptr<Node> mHead;
Node *mTail;
};

int main() {
Queue<std::string> q;
int numberOfItems{90000};
int i{0};
for(i=0; i<numberOfItems; ++i) {
q.push(std::to_string(i));
}
Queue<std::string>::Node *pointer{ q.mHead.get() };
while(pointer != q.mTail) {
std::cerr << *pointer->data << "\n";
pointer = pointer->Next.get();
}
return 0;
}

在我看来,段错误发生在类 Queue 的默认析构函数中。

我尝试检查类成员和 push 方法,但找不到我的错误。

最佳答案

在程序末尾破坏 std::unique_ptr 的链会破坏你的堆栈。您可以通过释放 Queue() 的析构函数中的 std::unique_ptr 来防止这种链式 react :

~Queue() {
mHead.release();
}

请注意,Queue 的内存已泄漏。更好的做法是循环遍历您的节点并一个一个地释放和销毁它们。

关于c++ - 为什么将项目添加到链表会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56845046/

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