如何修复valgrind内存?

时间:2018-03-29 17:58:38

标签: c valgrind

所以我有一个结构,当我启动一个时,我使用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;

有关

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

1 个答案:

答案 0 :(得分:4)

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

你想要的是:

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

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

将指针隐藏在typedef后面也是不好的做法,因为您使用可能会让读者感到困惑的指针并不明显,这可能是绊倒你的原因在这种情况下。