此代码创建一个 BST,填充它,并努力释放资源。release() 的两个版本如下所示:
typedef struct Node {
int d;
struct Node *left;
struct Node *right;
} Node;
int main() {
Node **tree = NULL;
tree = mkTree();
if (!tree) {
puts("problem\n");
return 1;
}
insert(7, tree);
insert(3, tree);
insert(9, tree);
insert(6, tree);
printTree(*tree);
release(tree);
free(tree);
return 0;
}
/* Make a new binary tree */
Node **mkTree() {
Node **t = malloc(sizeof **t);
return t;
}
/* insert datum d into tree */
bool insert(int d, Node **tree) {
Node *newptr = NULL;
if (tree == NULL) { /*ptr to rootptr NULL */
return false;
}
if (*tree == NULL) {
newptr = buildNode(d);
if (!newptr) {
return false;
}
*tree = newptr;
return true;
}
return insert(d, d < (*tree)->d ? &(*tree)->left : &(*tree)->right);
}
我不明白为什么 valgrind 声称在以下两种情况(I 和 II)中都释放了所有资源。我尝试使用 release() 清除每个节点,并且在 main 结束时,我调用 free(tree) 来清除在 main 中声明的 Node **tree。
一世。
/* release resources by passing Node **tree */
void release(Node **tree) {
if (*tree) {
Node *here = *tree;
release(&here->left);
release(&here->right);
}
free(*tree);
}
二、
/* passing Node *tree. this shouldn't free anything, right? */
void release(Node *tree) {
if (tree) {
Node *here = tree;
release(here->left);
release(here->right);
}
free(tree);
}
尽管有选择,运行这个程序有四个插入会给出
==5182== HEAP SUMMARY:
==5182== in use at exit: 0 bytes in 0 blocks
==5182== total heap usage: 5 allocs, 5 frees, 60 bytes allocated
这里发生了什么事?valgrind 是否只是统计 malloc 和 free 的数量?