简体   繁体   中英

How to fix valgrind memory?

So I have a structure and when I initiate one, I use malloc as so:

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 spits out:

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

write error pertains to q->len = 0;

I cannot tell what the problem is, am I allocating an incorrect amount of bytes?

It looks like QueueADT is a typedef for a pointer type. That means sizeof(QueueADT) evaluates to the size of the pointer, not what it points to. Since it seems that a pointer is 8 bytes on your system and that the struct in question is larger than that, you write past the end of allocated memory.

What you want instead is:

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

This allocates enough space for what q points to. Also, don't cast the return value of malloc .

It's also bad practice to hide a pointer behind a typedef , as it is not obvious that you're working with a pointer which can confuse the reader, and is probably what tripped you up in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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