c - 释放内存导致分段错误 11
问题描述
我正在尝试创建一个二叉搜索树。这是我的节点初始化函数:
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
语句的有效二叉搜索树。
如果有帮助,这是我的添加功能:
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;}
}
解决方案
对于初学者,函数 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);
调用未定义的行为。
推荐阅读
- laravel - 如何通过比较数据透视表中的值与 laravel 5.6 中所需表中的值来获取数据?
- node.js - NodeJS 生成 FFMPEG 进程不正确理解参数
- .net - VS 2013/Windows 10:添加/更新服务参考获取消息无法创建 SSL/TLS 安全通道
- git - 即使没有新的更改,也强制推送到 Gerrit
- git - 将 git 分支重置为较早的结帐
- string - 删除 kotlin 中的重音符号和变音符号
- mesh - meshlab 着色曲率 (APSS)
- flash - 这个数据是什么格式的?Sothink 的 Swf Quicker html5 导出,sprite.js
- python - 从零到一然后要求从零到一的另一个值
- javascript - 在 React 中使用 zindex 将 div 元素放在前面