不透明的指针valgrind

时间:2016-03-15 08:05:49

标签: c algorithm pointers data-structures tree

我目前正在用Opaque指针编写二叉树结构。但是,我对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 个答案:

答案 0 :(得分:2)

你正在为分配指针的内存。

typedef struct node * 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 :(得分:1)

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

应该是

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