【发布时间】:2015-12-18 21:00:13
【问题描述】:
我正在用 C 实现二叉搜索树的插入功能,但遇到了 malloc 的问题。
首先,我有一个树和节点结构
typedef struct Node {
double value;
struct Node *parent;
struct Node *right_child;
struct Node *left_child;
} Node;
typedef struct Tree {
struct Node *root;
} Tree;
这是我的插入函数,用于向树中插入一个值。
void insert(Tree *t, double v) {
Node *n = malloc(sizeof(Node));
n->left_child = malloc(sizeof(Node));
n->right_child = malloc(sizeof(Node));
n->parent = malloc(sizeof(Node));
n->value=v;
Node *x = t->root, *y = NULL;
//follow tree down until we reach a leaf of the tree
while (x) {
//save last non-NULL value. We will insert node n as a child to this leaf.
y = x;
if (n->value < x->value) {
x = x->left_child;
} else {
x = x->right_child;
}
}
//The parent of the node to insert is the leaf we reached
n->parent = y;
//If n is greater than y then it is its right child and vice-versa.
if (n->value > y->value) {
y->right_child = n;
} else {
y->left_child = n;
}
}
还有我的主要方法
int main(void) {
Node n1;
n1.value = 4;
n1.parent = NULL;
n1.left_child = NULL;
n1.right_child = NULL;
Tree t;
t.root = &n1;
insert(&t,2.0);
printf("In order traversal\n");
inOrderTraversalNode(t.root);
return EXIT_SUCCESS;
}
当我打印有序遍历代码时,我得到未定义的行为(例如:26815615859885194199148049996411692254958731641184786755447122887443528060147093953603748596333806855380063716372972101707507765623893139892867298012168192.000000)而不是正确的遍历。
我很确定问题出在insert 方法中的Node 创建。我认为问题在于堆栈中存在新节点,然后在 insert 函数退出时将其销毁 - 这就是导致遍历期间未定义行为的原因。但是,我认为malloc 将变量存储在堆上并使其全局可用。或者也许节点在堆上但指针在堆栈上?有人可以告诉我这里哪里出错了吗?
【问题讨论】:
-
我看到
main创建了一个Node并初始化了指向NULL的指针,但是当insert创建一个Node时,它通过调用malloc来初始化指针。但是malloc返回的Node本身并没有初始化。
标签: c binary-search-tree heap-memory stack-memory