c - 为什么 root 的值在 main 函数中打印为 0?

标签 c pointers malloc free

#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) 时会发生什么,它如何影响根变量?

最佳答案

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

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

关于c - 为什么 root 的值在 main 函数中打印为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30203823/

相关文章:

c - 指针数组 - 需要更大

c++ - 我如何获得 DirectFB 创建的 X Window 的 ID?

C 指针数组、转换和/或内存

linux - Malloc 在 64 位 Ubuntu 机器上失败

c - 为什么 mmap() 按降序返回地址,而 malloc() 按升序返回地址?

c++ - ctypes 中的 "char *pList"

c++ - 从 C/C++ 到内存的 GUI 窗口屏幕截图

c++ - 无法识别libgtest.so文件,无法识别格式

c - 将字符数组转换为字符串数组的问题

c - 使用 char 指针读取 int 值并返回它