将包含指向该类型队列的指针的结构推送到队列上时发生运行时崩溃
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;
}
谢谢!
编译器:适用于x86 的Microsoft(R)C/C++优化编译器19.00.23506版
操作系统:Windows 7专业版
在makeNode
函数中,将堆栈变量传递给子成员。当这个堆栈帧弹出时,内存被释放,剩下的是一个悬空指针。您应该使用new
或std::make_shared
在堆上进行分配,以便在弹出堆栈帧时不会释放内存。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Android NDK传感器向事件队列报告奇怪的间隔
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 为什么我的多线程作业队列崩溃
- 为什么下面的使用链表实现线性队列的代码返回垃圾值然后崩溃
- C++无锁队列与多个线程一起崩溃
- 当我插入元素时,C 优先级队列会崩溃
- 队列:取消队列功能使程序崩溃
- 将包含指向该类型队列的指针的结构推送到队列上时发生运行时崩溃
- 从队列中显示2D阵列后程序崩溃
- 队列用户APC - 抛出异常崩溃,可能是 mingw 错误
- 在我推入队列之前崩溃
- 尝试创建队列 - C++崩溃的问题
- 创建动态循环队列,元素输出正常,但程序崩溃
- 从队列中取出队列时程序崩溃
- 等待Boost的空闲队列.原子示例崩溃