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