【问题标题】:Opaque pointer valgrind不透明指针 valgrind
【发布时间】:2016-06-30 13:20:25
【问题描述】:

我目前正在使用不透明指针编写二叉树结构。但是,我对 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;

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

【问题讨论】:

    标签: c algorithm pointers data-structures tree


    【解决方案1】:
    NODE tree = (NODE) malloc(sizeof(NODE)); this line is incorrect. 
    

    应该是

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

    【讨论】:

      【解决方案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所指向的内容”


      附:do not cast the result of malloc.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-15
        • 2011-02-12
        • 1970-01-01
        • 2017-02-12
        • 1970-01-01
        • 2013-07-12
        相关资源
        最近更新 更多