我正在尝试创建一个二进制搜索树。这是我的节点初始化函数:
node_t* node_init(int val){
node_t* n1 = malloc(sizeof(node_t));
n1->value = val;
n1->leftNode = NULL;
n1->rightNode = NULL;
return n1;
}因为我在记忆中,我知道我应该把它释放到别的地方去。我这样做的主要方法是:
int main(){
tree_t t1;
tree_init(&t1);
node_t* n1 = node_init(5);
node_t* n2 = node_init(7);
t1.count += add(n1, &(t1.root));
t1.count += add(n2, &(t1.root));
//free(n1);
//free(n2);
print_tree(t1.root);
}然而,当我取消对空闲行的注释时,我会得到一个分段错误。我不知道为什么会这样,因为一旦内存被分配,我就必须释放它。在我的add函数中,我不进行任何释放,代码不使用free语句输出有效的二进制搜索树。
如果有帮助,下面是我的add函数:
int add(node_t* n, node_t** tn){
if(*tn == NULL){*tn = n; return 1;}
if(n->value < (*tn)->value){add(n, &((*tn)->leftNode));}
else if (n->value > (*tn)->value){add(n, &((*tn)->rightNode));}
else{return 0;}
}发布于 2021-06-06 17:07:56
首先,函数add具有未定义的行为,因为在某些执行路径中,它不返回任何内容。
你需要写
int add(node_t* n, node_t** tn){
if(*tn == NULL){*tn = n; return 1;}
if(n->value < (*tn)->value){ return add(n, &((*tn)->leftNode));}
else if (n->value > (*tn)->value){ return add(n, &((*tn)->rightNode));}
else{return 0;}
}这些语句都是免费的
free(n1);
free(n2);不要在树中将n1和n2设置为NULL。所以这个电话
print_tree(t1.root);调用未定义的行为。
https://stackoverflow.com/questions/67861607
复制相似问题