将包含指向该类型队列的指针的结构推送到队列上时发生运行时崩溃

Runtime crash when pushing onto a queue a struct containing a pointer to that type of queue

本文关键字:队列 崩溃 运行时 结构 包含指 类型 指针      更新时间:2023-10-16

我正在尝试创建一个树,其中每个节点(结构)都有一个字符串字段作为其名称和一个队列<节点>*包含其子节点的队列的字段。

下面的示例代码是一个小程序,它隔离了我在更大、更复杂的程序中收到的错误。它消除了与我的错误无关的任何内容,但类似于有问题的原始代码。我在与完整代码相同的位置收到了相同的错误,这是运行时崩溃。编译器在编译时不会给我任何警告。

当我试图将节点推送到其中一个队列时,就会发生崩溃,该队列在从指针延迟后通过引用传递到函数中。

代码中包含数字的注释显示了它的执行顺序。

#include <string>
#include <queue>
#include <iostream>
using namespace std;
using std::string;
using std::queue;
// the tree node structure
typedef struct Node
{
    string name; // the name of this node
    queue<Node>* children; // a queue containing the child nodes
} Node;
Node makeNode(string name)
{
    queue<Node> children = {}; // 2, 7, 12
    Node n = {name, &children}; // 3, 8, 13
    return n; // 4, 9, 14
}
void funcTwo(queue<Node>& nodes)
{
    Node n = makeNode("Child of Child of Root"); // 11
    cout << "Program prints this." << endl; // 15
    nodes.push(n); // PROGRAM CRASHES HERE
    cout << "Program does not print this." << endl;
}

void funcOne(queue<Node>& nodes)
{
    Node n = makeNode("Child of Root"); // 6
    funcTwo(*n.children); // 10
    nodes.push(n);
}
int main()
{
    Node root = makeNode("Root"); // 1
    funcOne(*root.children); // 5
    return 0;
}

谢谢!

编译器:适用于x86 的Microsoft(R)C/C++优化编译器19.00.23506版

操作系统:Windows 7专业版

makeNode函数中,将堆栈变量传递给子成员。当这个堆栈帧弹出时,内存被释放,剩下的是一个悬空指针。您应该使用newstd::make_shared在堆上进行分配,以便在弹出堆栈帧时不会释放内存。