如何修复 valgrind 内存?

How to fix valgrind memory?

所以我有一个结构,当我启动一个结构时,我这样使用 malloc:

typedef struct node{ 
    void *value;
    struct node *next;
} node;

typedef struct QueueADT{
    int (*cmp)(const void*a, const void*b);
    struct node *front;
    int len;
    struct node *back;
} * QueueADT;




QueueADT que_create( int (*cmp)(const void*a, const void*b) ) {
    printf("%lu\n",sizeof(QueueADT));
    QueueADT q = (QueueADT)malloc(sizeof(QueueADT));
    if (q == NULL) {return NULL;}
    q->cmp = cmp;
    q->len = 0;
    return q;
}

valgrind吐槽:

Invalid write of size 4
Address 0x5204490 is 8 bytes after a block of size 8 alloc'd

写入错误与 q->len = 0 有关;

我不知道是什么问题,我分配的字节数不正确吗?

看起来 QueueADT 是指针类型的 typedef。这意味着 sizeof(QueueADT) 评估指针的大小,而不是它指向的内容。由于在您的系统上指针似乎是 8 个字节,并且所讨论的结构比这更大,因此您写入已分配内存的末尾。

你想要的是:

QueueADT q = malloc(sizeof(*q));

这为 q 指向的内容分配了足够的 space。另外,don't cast the return value of malloc.

将指针隐藏在 typedef 后面也是不好的做法,因为您使用的指针并不明显,这可能会混淆 reader,并且可能是您绊倒的原因在这种情况下。