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

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

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

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

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

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

#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;
}

谢谢!

Compiler: Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x86

OS: Windows 7 Professional

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