C 不透明指针研磨

C 不透明指针研磨,c,algorithm,pointers,data-structures,tree,C,Algorithm,Pointers,Data Structures,Tree,我目前正在编写一个带有不透明指针的二叉树结构。然而,我在Valgrind中有无效的写入 Tree.c: struct node{ int key; struct node *left, *right, *parent; }; NODE nodeInit(void) { NODE tree = (NODE) malloc(sizeof(NODE)); tree->key = -1; //Error with the 3 lines below

我目前正在编写一个带有不透明指针的二叉树结构。然而,我在Valgrind中有无效的写入

Tree.c:

struct node{
    int key;
    struct node *left, *right, *parent;
};

NODE nodeInit(void)
{
    NODE tree = (NODE) malloc(sizeof(NODE));
    tree->key = -1;
    //Error with the 3 lines below
    tree->right = NULL;
    tree->left = NULL;
    tree->parent = NULL;
    return tree;
}
Tree.h:

typedef struct node* NODE;

注意:我不能更改头文件。

您正在为指针分配内存

typedef struct node*node表示从现在起,
节点
是“指向
结构节点
的指针”的别名。因此
malloc(sizeof(NODE))
分配
sizeof struct NODE*
字节的内存-足够的内存来容纳指向结构的指针,而不足够的内存来容纳结构

使用以下任一选项:

NODE tree = malloc(sizeof *tree);

前者可能更好,因为它隐含的意思是“分配足够的内存来包含指针
树所指向的内容”


附言

应该是

NODE tree = (NODE) malloc(sizeof(struct node));
NODE tree = (NODE) malloc(sizeof(NODE)); this line is incorrect. 
NODE tree = (NODE) malloc(sizeof(struct node));