【发布时间】: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->data具有未定义的行为,因为root是无效指针(它指向内存的已释放部分)。