2015-05-13 55 views
0
#include <stdio.h> 
#include <stdlib.h> 

struct nodeTree { 
    int data; 
    struct nodeTree* left; 
    struct nodeTree* right; 
}; 

struct nodeTree* insertRoot(struct nodeTree** root, int data) { 
    if(!(*root)) { 
     struct nodeTree *temp = malloc(sizeof(struct nodeTree)); 
     if(!temp) { 
      exit(-1); 
    } 

     temp->data = data; 
     temp->left = 0; 
     temp->right = 0; 
     (*root) = temp; 
     free(temp); 
     return *root; 
    } 
} 



int main() { 
    struct nodeTree *root = NULL; 
    root = insertRoot(&root,10); 
    printf("%d\n",root->data); 
    return 0; 
} 

我写了一个函数来在二叉树的根中插入一个值。在我的插入函数中,我分配了一个临时节点,并且在将值插入到临时节点后,我将临时节点分配给了根节点并释放临时节点。我知道我可以直接将malloc放入根变量并将数据分配给它。当free(temp)被调用时会发生什么,它会如何影响根变量?为什么在主函数中root的值被打印为0?

+0

'root-> data'具有未定义的行为,因为'root'是一个无效指针(它指向内存的一个释放部分)。 –

回答

2

你不应该free()temp,因为你仍然指向它与root,它们指向同一个数据,从而释放temp做免费*root了。

至于为什么它的打印0这只是一个巧合,因为有free()root的功能,你分配它,并在main()访问它调用未定义的行为,后果可能是printf()版画,0,这是一个行为,并且由于它是未定义的,所以其他行为实际上是可能的。

+0

我不清楚的是,我已经阅读无处不在,无论你malloc应该是免费的()编辑。使用相同的临时变量什么是编写代码的正确方法? – EnthusiatForProgramming

+0

@ user1534214你当然需要释放malloc内存。但只有当你不需要它了。显然在这种情况下,你仍然需要这样的记忆,所以你不应该释放它。通常,当将该节点从树中删除/移除时,将释放内存。 – kaylum

相关问题