2016-03-15 89 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));