读取访问权限冲突 0xCDCDCDCD

0

运行环境:VS2019(C语言编写)

问题:执行到Enqueue的以下语句时,引发读取访问权限冲突,错误显示堆内存未初始化,个人能力不足,不知道怎么处理

node->val = root->val;

程序目的:实现二叉树的层序遍历

提示:由于程序执行递归所以需要多次输入-1结束,程序没有陷入死循环。

程序完整代码:

/***
二叉树的层序遍历
利用队列实现
***/
#include<malloc.h>
#include<stdio.h>
#include<stdbool.h>
typedef struct BiTree {
	struct BiTree* left;
	struct BiTree* right;
	struct BiTree* next;
	int val;
}BiNode;
typedef struct queue {
	BiTree* front;
	BiTree* rear;
}Queue;
void CreateBiTree(BiNode **root){
	if (root == NULL) return;
	int value = -1;
	scanf_s("%d", &value);
	if (value == -1) root = NULL;
	else {
		*root = (BiNode*)malloc(sizeof(BiNode));
		if (*root == NULL) return;
		(*root)->val = value;
		printf("请输入左子树的值(-1结束):\n");
		CreateBiTree(&(*root)->left);
		printf("请输入右子树的值(-1结束):\n");
		CreateBiTree(&(*root)->right);
	}
}
/***
队列建立多使用头节点
方便结点的next指针初
始化
头插法不行必须尾插法
**/
void CreateQueue(Queue *q,int num){
	BiTree* head =(BiTree*)malloc(sizeof(BiTree));
	if (head == NULL) return;
	q->front=q->rear=head;
	q->front->next = q->rear->next = NULL;
	while (num) {
		BiNode* node =(BiNode*)malloc(sizeof(BiNode));
		if (node == NULL) return;
		node->next = q->rear->next;
		q->rear->next = node;
		q->rear = node;
		num--;
	}
}
/****
链式队列入队操作
***/
void Enqueue(struct BiTree *root,Queue *q){
	BiTree* node =(BiNode*)malloc(sizeof(BiNode));
	if (node == NULL) return;
	/**
	读取值时报读取权限的错误
	***/
	node->val = root->val;
	node->next = q->rear->next;
	q->rear->next= node;
	q->rear = node;
}
/***
链式队列判断队列
是否已经空了
****/
bool IsEmpty(Queue* q) {
	return q->rear == q->front ? true : false;
}
/***
链式队列出队操作
***/
BiNode* Dequeue(Queue *q){
	if (IsEmpty(q)) return NULL;
	BiNode* tmp = q->front->next;
	q->front->next = q->front->next->next;
	printf("%d已经执行了出栈操作!\n",tmp->val);
	if (q->rear == tmp) q->rear = q->front;
	return tmp;
}
void  DestoryQueue(Queue *q){
	while (!IsEmpty(q)) {
		BiNode* tmp = q->front;
		printf("%d结点已经销毁!\n", tmp->val);
		q->front = tmp->next;
		free(tmp);
		tmp = NULL;
	}
}
void levelOrder(struct BiTree* root) {
	Queue q;
	CreateQueue(&q, 100);
	while (root!= NULL) {
		printf("%d ", root->val);
		if (root->left != NULL) {
			Enqueue(root->left, &q);
		}
		else if (root->right != NULL) {
			Enqueue(root->right, &q);
		}
		if (!IsEmpty(&q)) {
			root= Dequeue(&q);
		}
		else {
			root = NULL;
		}
	}
	DestoryQueue(&q);
}
int main() {
	BiNode* root;
	CreateBiTree(&root);
	levelOrder(root);
	return 0;
}
ava
凤栖梧

2020-11-22

0

levelOrder(root); 这行加断点

然后执行程序。

断下来后,添加监视变量 root

会看到树的终结点没有赋值 NULL

因此导致你后续遍历时判断不到 NULL 所以出错。

ava
BestAns

2020-11-22

问题已经解决了,这个程序的主要问题是复制结点的值的时候没有复制左右子树的结点值,同时结点初始化时也没有将叶子结点设置为空,主要这两个问题 -  凤栖梧  2020-11-22
技术讨论社区