gpt4 book ai didi

c - 我是否需要在 BinaryTree 中释放根或数据?

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:29 25 4
gpt4 key购买 nike

我有个问题...如果我有这样的二叉树:

typedef struct
{
char* text;
char* line;
struct Node* left;
struct Node* right;
}Node

并且有一个启动函数:

Node *start(Node* ptr)
{
if(ptr == NULL)
{
ptr = (Node*)malloc(sizeof(Node));
ptr->text = "some text";
ptr->line = "another text";
ptr->left = NULL;
ptr->right = NULL;
}
return (ptr);
}

还有一个在二叉树中添加左 child 的功能,如果根不为空,这里我必须给我的文本和行动态内存。

  Node* addNode(Node* ptr)
{
if(ptr != NULL)
{
Node* leftNode = (Node*)malloc(sizeof(zeiger));
char* text = (char*) malloc(100*sizeof(char));
char* line = (char*) malloc(100*sizeof(char));

line = "some text 2";
text = "another text";
if(leftNode !=NULL)
{
leftNode->text = text;
leftNode->line = line;
leftNode->right = NULL;
ptr->left = leftNode;
}
return leftNode;
}
return ptr;

现在的问题是我想释放树中的所有东西,所以我有一个这样的函数来调用他自己,如果 left 或 right 或 root 不为 NULL。所以我看到了一些代码,我应该释放根目录而不是数据。

void freeTree(Node* root)
{
while(1)
{
if(root == NULL)
{
break;
}
else if (root->left != NULL)
{
freeTree(root->left);
root->left = NULL;
}
else if (root->right) {
freeTree(root->right);
root->right = NULL;
}
else
{
free(root);
}
}
}

主要.c

int main(int argc, char const *argv[]) {

Node* root = NULL;
root = start(root);
root = addNode(root);
freeTree(root);
return 0;
}

最佳答案

你不应该释放你没有 malloc 的内存。

这里第一个节点的指针指向一个字符串文字。你不应该对它们调用 free()

您还应该在初始节点中分配内存,然后尝试复制该字符串文字。现在每个节点都是相似的。

现在释放每个节点的内存。先做哪个节点?后序遍历就是其中之一。首先是 child ,然后是 parent 应该被释放,否则你会发生内存泄漏。

void freeTree(Node *root){
if( root ){
freeTree(root->left);
freeTree(root->right);
free(root->text); // root->text was allocated calling malloc
free(root->line); // same for root->line
free(root);
}
}

root->text was allocated calling malloc - 您必须动态分配才能对其调用 free。在您的代码中,初始节点的 text 指向字符串文字。您需要按照答案中提到的正确方式进行操作 - (分配 - 并将字符串复制到新分配的内存中)。

关于c - 我是否需要在 BinaryTree 中释放根或数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47650996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com