【发布时间】:2022-01-24 20:27:52
【问题描述】:
#include <stdlib.h>
#include <stdio.h>
#include "sorted_tree.h"
int insert_value(int value, struct TreeNode *n) {
if (value < n->value) {
if (n->left_child == NULL) {
struct TreeNode t = {0};
struct TreeNode *tpointer = &t;
tpointer->value = value;
tpointer->left_child = NULL;
tpointer->right_child = NULL;
n->left_child = tpointer;
printf("links eingefügt\n");
}
else {
insert_value(value, n->left_child);
}
return 0;
}
else if (value > n->value) {
if (n->right_child == NULL) {
struct TreeNode t = {0};
struct TreeNode *tpointer = &t;
tpointer->value = value;
tpointer->left_child = NULL;
tpointer->right_child = NULL;
n->right_child = tpointer;
printf("rechts eingefügt\n");
}
else {
insert_value(value, n->right_child);
}
return 0;
}
else {
return 1;
}
}
void print_inorder(struct TreeNode *n) {
if (n == NULL) {
printf("r");
return;
}
else {
print_inorder(n->left_child);
printf("%d ", n->value);
print_inorder(n->right_child);
}
}
int main() {
struct TreeNode t = {0};
struct TreeNode *tpointer = &t;
tpointer->value = 5;
tpointer->left_child = NULL;
tpointer->right_child = NULL;
insert_value(6, tpointer);
printf("%d", tpointer->right_child->value);
printf("%d", tpointer->right_child->value);
}
main 中的第一个 printf() 输出正确的“6”,但第二个输出一个随机数,好像地址已更改。 6 应该插入到右子节点中,所以我期望 66 作为输出。为什么会发生这种情况,我该如何解决?
【问题讨论】:
-
寻求调试帮助的问题通常应包括问题的minimal reproducible example。
-
n->right_child=tpointer;不起作用,因为struct TreeNode t={0};仅在if块内具有生命周期。保留对它的引用并在此之外使用它,这会导致未定义的行为。需要使用动态分配来制作这些节点。例如,struct TreeNode *tpointer = malloc(sizeof(*tpointer)); -
@AndreasWenzel:你为什么怀疑它?是 UB,但不是难以置信的 UB。
-
对
printf()的调用会覆盖以前用于right_child的堆栈内存。 @AndreasWenzel -
@Barmar:啊,是的,你可能是对的。我已删除我的评论。
标签: c recursion struct binary-search-tree function-definition