【问题标题】:Runtime crash when pushing onto a queue a struct containing a pointer to that type of queue将包含指向该类型队列的指针的结构推入队列时运行时崩溃
【发布时间】:2016-07-30 09:43:33
【问题描述】:

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

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

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

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

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

谢谢!

编译器:Microsoft (R) C/C++ 优化编译器版本 19.00.23506 for x86

操作系统:Windows 7 专业版

【问题讨论】:

    标签: c++ pointers struct queue pass-by-reference


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      相关资源
      最近更新 更多