我写了一个二叉搜索树,它工作正常,但我不确定我的程序是否释放了所有的记忆.
这是我对树节点的定义
typedef struct node {
int val;
struct node *left, *right;
} nodeOfTree;
Run Code Online (Sandbox Code Playgroud)
我写这个函数来输出结果并释放所有节点,似乎答案是正确的但是记忆没有被释放.
void outputAndDestroyTree(nodeOfTree *root) {
if (!root) {return;}
outputAndDestroyTree(root->left);
printf("%d ", root->val);
outputAndDestroyTree(root->right);
free(root); // I free this pointer, but after doing that, I can still access this pointer in the main() function
}
Run Code Online (Sandbox Code Playgroud)
这是否意味着我无法在递归函数中释放一段记忆?谢谢~~~~~
更新:谢谢大家〜
你的代码似乎没问题,但释放分配的内存不会神奇地设置它的引用指针NULL.由于您没有为指针设置新值,因此旧地址将保持不变.也许你甚至可以在不崩溃的情况下从中读取,尽管它是未定义的行为.
如果你想NULL在释放内存后将它设置为,那么就这样做.outputAndDestroyTree(root->left);然后打电话root->left = NULL;.