Valgrind mysterious invalid write of size 8 error

Viewed 56

I've searched far and wide and found no answers, so the best option is to ask my own question. I'm currently doing an assignment for university which requires us to build a node that has a key and value string.

I structured the following node, alongside the following two functions:

typedef struct node_t
{
    char *key;
    char *data;
} * Node;

Node nodeCreate()
{
    Node node = NULL;
    node = malloc(sizeof(Node));
    if (node == NULL)
        return NULL;
    node->key = NULL;
    node->data = NULL;
    return node;
}
void nodeDestroy(Node node)
{
    if (node == NULL)
        return;
    if (node->key != NULL)
        free(node->key);
    if (node->data != NULL)
        free(node->data);
    free(node);
}

However, the code above gives me the following error: Valgrind error message

Now, this is the plot twist. If I remove the code for the data, the code works fine and valgrind does not give any issues.

I can't find any fixes for this, and it's holding me up on a big assignment, and I don't know what to do. Any help is appreciated.

3 Answers
node = malloc(sizeof(Node));

Is allocating space that is enough for only one pointer.

On the other hand, the structure has 2 pointers, so typically it will be larger than one pointer.

The line should be

node = malloc(sizeof(struct node_t));

or

node = malloc(sizeof(*node));

to allocate sufficient space.

node = malloc(sizeof(Node));

The above will only allocate the necessary size to store a pointer to struct node_t because of how you defined Node.

Either change the line to:

node = malloc(sizeof(*node));

Or define Node as an alias of struct node_t instead of a pointer to it.

in

malloc(sizeof(Node))

you do not allocate a node_t as you expected but a pointer to it

replace it by

malloc(sizeof(struct node_t))

It is a bad idea to define a type pointer, that produces that kind of error, replace

typedef struct node_t
{
    char *key;
    char *data;
} * Node;

by

typedef struct node_t
{
    char *key;
    char *data;
} Node;

and do not mask the pointer everywhere

Related