C语言二叉树插入时结构体int值异常:为何输出随机值而非3?
二叉树插入后子节点值输出垃圾值的问题解决
你的代码里printf("%d\n", root.pLeft->value)输出随机垃圾值,核心原因是局部变量的生命周期问题:
在insert函数中,你定义的newLeft和newRight是栈上的局部变量,当函数执行完返回时,栈上的这些变量会被系统销毁,内存被回收。此时current->pLeft和current->pRight指向的是已经失效的内存地址,后续访问就会得到随机的垃圾数值。
修正方案:用动态内存分配创建节点
堆内存分配的节点不会随函数返回而销毁,需要手动调用free释放。修改后的代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Node { int value; struct Node *pLeft; struct Node *pRight; }; // 创建空节点(value=0,左右指针为空) struct Node* createEmptyNode() { struct Node *node = (struct Node*)malloc(sizeof(struct Node)); if (!node) { puts("内存分配失败"); exit(1); } node->value = 0; node->pLeft = NULL; node->pRight = NULL; return node; } void insert(struct Node *root, int value) { // 禁止插入值0 if (value == 0) return; struct Node *current = root; while (current->value != 0) { if (value < current->value) { // 左子节点为空则先创建空节点 if (!current->pLeft) current->pLeft = createEmptyNode(); current = current->pLeft; } else { // 右子节点为空则先创建空节点 if (!current->pRight) current->pRight = createEmptyNode(); current = current->pRight; } } current->value = value; } int main() { struct Node root; root.value = 0; root.pLeft = NULL; root.pRight = NULL; insert(&root, 4); insert(&root, 3); printf("%d\n", root.value); if (root.pLeft) printf("%d\n", root.pLeft->value); // 注意:实际使用时要实现销毁函数释放所有堆内存,避免泄漏 return 0; }
额外注意点
- 初始的
root节点是栈变量,记得初始化左右指针为NULL,避免野指针。 - 访问子节点前先判断指针是否为空,防止空指针访问崩溃。
- 动态分配的内存最终要手动释放,建议后续写一个递归的销毁函数,遍历所有节点调用
free。
内容的提问来源于stack exchange,提问作者CoderBendl
相关产品推荐
相关产品推荐

