导致Segmentation错误的结构中的矢量

vector in struct causing Segmentation fault

本文关键字:结构 错误 导致 Segmentation      更新时间:2023-10-16

我正试图为每个节点构建一个具有未知数量子节点的树。为此,我构造了一个结构,其中包含子节点的向量,这样我就可以根据需要增加它的大小。以下代码是我如何定义结构的:

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