2016-03-15 106 views
1

我目前正在用不透明指针写一个二叉树结构。但是,我用Valgrind写入了无效的内容。不透明指针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; 

注:我不能改变的头文件。

回答

2

你正在分配内存只是的指针。

typedef结构节点* NODE意味着从现在开始NODE“的指针struct node的别名。因此malloc(sizeof(NODE))分配sizeof struct node *字节的内存 - 足够的内存来容纳一个指向你的结构的指针,而不足以容纳你的结构的内存。

二者必选其一:

NODE tree = malloc(sizeof *tree); 

NODE tree = malloc(sizeof (struct node)); 

前者也许是更好,因为它隐含意味着“分配足够的内存来包含这是由指针指向tree


P.S.,do not cast the result of malloc

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

应该

NODE tree = (NODE) malloc(sizeof(struct node));