1

I'm currently writing a binary tree structure with Opaque Pointer. However, I have Invalid writes with 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;

Note : I mustn't change the header file.

Gaulthier
  • 320
  • 7
  • 16

2 Answers2

2

You're allocating memory for just the pointer.

typedef struct node* NODE means that from now on NODE is an alias for "a pointer to struct node". Thus malloc(sizeof(NODE)) allocates sizeof struct node * bytes of memory - enough memory to hold a pointer to your structure, not enough to memory to contain your structure.

Use either:

NODE tree = malloc(sizeof *tree);

or

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

The former is perhaps better, because it implicitly means "allocate enough memory to contain that which is pointed to by the pointer tree".


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

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

It should be

NODE tree = (NODE) malloc(sizeof(struct node));
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Naveen.sn
  • 72
  • 6