简体   繁体   English

Valgrind 神秘的无效写入大小为 8 错误

[英]Valgrind mysterious invalid write of size 8 error

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 错误信息

Now, this is the plot twist.现在,这是 plot 扭曲。 If I remove the code for the data, the code works fine and valgrind does not give any issues .如果我删除数据的代码,代码工作正常,valgrind 不会给出任何问题

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.任何帮助表示赞赏。

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.另一方面,该结构有 2 个指针,因此通常它会大于一个指针。

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 .由于您定义Node的方式,上述内容只会分配必要的大小来存储指向struct node_t的指针。

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.或者将 Node 定义为struct node_t的别名,而不是指向它的指针。

in

malloc(sizeof(Node))

you do not allocate a node_t as you expected but a pointer to it您没有按预期分配node_t而是指向它的指针

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并且不要到处掩盖指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM