【问题标题】:Why the value of root is printed as 0 in main function?为什么 root 的值在 main 函数中打印为 0?
【发布时间】:2015-05-13 00:48:10
【问题描述】:
#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;
}

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

【问题讨论】:

  • root-&gt;data 具有未定义的行为,因为 root 是无效指针(它指向内存的已释放部分)。

标签: c pointers malloc free


【解决方案1】:

你不应该free()temp,因为你仍然用root指向它,它们指向相同的数据,因此释放temp也释放*root

至于为什么它打印 0 这只是一个巧合,因为在分配它的函数中有 free()ed root,并在 main() 中访问它会调用未定义的行为,结果可能是 @ 987654330@ 打印,0,这是一种行为,由于它是未定义的,因此任何其他行为实际上都是可能的。

【讨论】:

  • 我不清楚的是,我到处都读过,无论你 malloc 应该是 free() ed。使用相同的临时变量编写代码的正确方法是什么?
  • @user1534214 当然,您确实需要释放 malloc 内存。但只有当你不再需要它时。显然,在这种情况下,您仍然需要该内存,因此您不应该释放它。通常,当要从树中删除/移除该节点时,您会释放内存。
猜你喜欢
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2012-02-25
  • 2010-12-13
相关资源
最近更新 更多