我昨天花了几个小时在程序中找到一个错误.我可以将其分解为以下内容.代码没有多大意义.但问题是,如果我遗漏了这条线
BST root2 = (BST) malloc(sizeof(BST));
Run Code Online (Sandbox Code Playgroud)
在函数fillTree()中,程序执行它应该执行的操作.但是取消注释该行会导致fillTree()中BST root3的数据字段从NULL变为不同的值.但我不明白为什么会这样.
所以没有注释我得到以下输出:
root3->data is still null!
Run Code Online (Sandbox Code Playgroud)
但它应该(行评论):
root3->data is still null!
root3->data is still null!
root3->data is still null!
root3->data is still null!
Run Code Online (Sandbox Code Playgroud)
请帮我!
非常感谢你!
#include <stdio.h>
#include <stdlib.h>
typedef struct BSTTag{
struct BSTTag* lNode;
struct BSTTag* rNode;
void *data;
int (*compare)(void*, void*);
} *BST;
BST createTree(BST root) {
if(root == NULL) {
BST bst = (BST) malloc(sizeof(BST));
bst->lNode = NULL;
bst->rNode = NULL;
bst->data = NULL;
return bst;
}
return root;
}
BST fillTree(BST root, int n) {
int i;
BST root3 = NULL;
// error occurrs if this line is not commented
//BST root2 = (BST) malloc(sizeof(BST));
for(i = n; i > 0; i--) {
int *rd = (int *)malloc(sizeof(int));
*rd = i;
if(i == n) {
root3 = createTree(NULL);
}
if(root3->data == NULL) {
printf("root3->data is still null!\n");
}
}
return root;
}
int main(void) {
fillTree(NULL, 4);
}
Run Code Online (Sandbox Code Playgroud)
您只为指针分配空间,
BST bst = (BST) malloc(sizeof(BST));
Run Code Online (Sandbox Code Playgroud)
但你使用它就好像你为结构分配了空间,
BST createTree(BST root) {
if(root == NULL) {
BST bst = (BST) malloc(sizeof(BST));
bst->lNode = NULL;
bst->rNode = NULL;
bst->data = NULL;
return bst;
}
return root;
}
Run Code Online (Sandbox Code Playgroud)
因此写入已分配的内存,调用未定义的行为.
你应该分配适当的大小,
BST bst = (BST) malloc(sizeof(*bst));
Run Code Online (Sandbox Code Playgroud)