在程序结束时释放内存有问题。
这是一个来自学校的练习,用ADT实现二叉树,用char数据类型实现特定的实现。
释放代码:
void free_tree(TreeNode *root){
TreeNode *cur;
if (!root) return;
else{
cur = root;
free_tree(cur->left);
free_tree(cur->right);
free(cur->key); //throws an error!
free(cur);
} }
这是我对密钥本身进行malloc的地方(问题可能在这里):
puts("Please enter a value for key of new node");
_flushall();
scanf("%s",&buffer);
user_input = (char *) malloc(sizeof(char)*(strlen(buffer)+1));
strcpy(user_input,buffer);
user_input[strlen(buffer)+1] = '\0';
p_node = create_tree_node(user_input); //this function append the new data to a new node, returns *TreeNode
insert_node_by_value(&root,p_node,str_comp);
break;
这就是我得到的错误:
顺便说一句,释放节点本身工作得很好!
我将感谢您的帮助以及关于代码功能的任何提示和评论。
函数.c的完整代码粘贴可以在以下位置找到:
http://pastebin.com/TqaNK5v8-功能
最佳答案
我唯一能找到的问题是:
user_input[strlen(buffer)+1] = '\0';
因为用户输入有'strlen(buffer)+1'元素,所以它只能从0到strlen(buffer)进行索引。要解决这个问题非常简单,请删除该行,strcpy行为是复制源字符串的0。
关于c - 我尝试释放时检测到堆损坏(无效*键),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14413091/