导致Segmentation错误的结构中的矢量
vector in struct causing Segmentation fault
我正试图为每个节点构建一个具有未知数量子节点的树。为此,我构造了一个结构,其中包含子节点的向量,这样我就可以根据需要增加它的大小。以下代码是我如何定义结构的:
typedef struct Tree_node{
int item;
int count;
struct Tree_node *parent; //point to the parent node
vector<struct Tree_node *> child; //a vector of child node, can grow in size
}TREE_NODE;
typedef struct{
vector<TREE_NODE *> root;
}FP_TREE;
我在网上发现一些文章说结构中的向量是完美的。然而,当我尝试执行以下示例代码时,终端显示"分段故障">
FP_TREE *tree = (FP_TREE *)malloc(sizeof(FP_TREE));
TREE_NODE *test = (TREE_NODE *)malloc(sizeof(TREE_NODE));
tree->root.push_back(test); //sth wrong here
编译代码时没有任何错误。我怀疑,随着树的向量的增长,它超过了最初分配给它的内存大小,从而导致了一些潜在的问题。我是错过了什么,还是有更好的方法来建造这种树?非常感谢您的建议。
在C++中,使用malloc的方式是未定义的行为,因为它不执行对象初始化,这意味着它没有调用向量的构造函数(但还有其他事情没有完成,例如初始化vtable(如果有的话))。
在您的示例中,您应该使用new:
FP_TREE *tree = new FP_TREE();
TREE_NODE *test = new TREE_NODE();
tree->root.push_back(test);
//This code will leak unless you call delete tree; delete test;
但在C++中,您真正应该做的是依赖RAII,避免使用原始指针(如果需要使用指针,请使用智能指针,如std::unique_ptr)
FP_TREE tree{};
TREE_NODE test{};
tree.root.push_back(&test);
//Be careful, you can end up with a dangling pointer stored in
//tree.root if test goes out of scope
相关文章:
- C++ 结构错误"调用'erase'没有匹配函数
- 尝试传递结构数组,但出现"无法将'结构'转换为'结构*'错误
- 结构错误:"no matching function for call to "
- UE4 数据表结构错误
- STL 对priority_queue<int、结构>错误
- C :用于体系结构错误的经典未定义符号
- 体系结构错误的未定义符号
- 奇怪的用户定义的比较结构错误,用于C++中的priority_queue
- 模板结构错误
- C++结构错误 - 错误 C2061:语法错误:标识符
- C++ 结构错误的前向声明
- 结构错误"uninitialized reference member"
- 使用 MPL::fold 与占位符和我自己的结构错误
- C++结构错误"No matching function for call..."
- 插入映射<字符串,结构>错误
- CPP 头文件结构错误
- 矢量和结构错误
- C++ 结构 - 错误 1 错误 C2143:语法错误:缺少'*'之前的';'
- 结构错误的构造函数(调用类的构造函数 denconstructor,用于填充结构)
- 结构错误与C++