C程序奇怪的行为-指针和内存
我昨天花了几个小时在我的程序中发现了一个bug。我可以把它分解为以下几点。代码没有多大意义。但问题是,如果我不排队C程序奇怪的行为-指针和内存,c,pointers,memory,C,Pointers,Memory,我昨天花了几个小时在我的程序中发现了一个bug。我可以把它分解为以下几点。代码没有多大意义。但问题是,如果我不排队 BST root2 = (BST) malloc(sizeof(BST)); 在函数fillTree中,程序执行它应该执行的操作。但取消对该行的注释会导致fillTree中BST root3的数据字段从NULL变为其他值。 但我不明白为什么会这样 因此未注释的我得到以下输出: root3->data is still null! 但应该注意的是: root3->da
BST root2 = (BST) malloc(sizeof(BST));
在函数fillTree中,程序执行它应该执行的操作。但取消对该行的注释会导致fillTree中BST root3的数据字段从NULL变为其他值。
但我不明白为什么会这样
因此未注释的我得到以下输出:
root3->data is still null!
但应该注意的是:
root3->data is still null!
root3->data is still null!
root3->data is still null!
root3->data is still null!
请帮帮我
多谢各位
#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);
}
您只为指针分配空间
BST bst = (BST) malloc(sizeof(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 bst = (BST) malloc(sizeof(*bst));
您只为指针分配空间
BST bst = (BST) malloc(sizeof(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 bst = (BST) malloc(sizeof(*bst));
那么,你想知道malloc SizeOfbsttag还有一种类型定义的指针被认为是有害的。你说得对!我第一次这么做了,我不打算再做了^^^那么你想知道malloc SizeOfbsttag还有一种类型定义的指针被认为是有害的。你说得对!我第一次这么做了,我再也做不到了^^