1

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?

Adam G.
  • 107
  • 1
  • 8

1 Answers1

4

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • thanks for the quick reply! Nice assumption! It's all good now. also thanks for the explanation about typedef pointers, ill take that into consideration – Adam G. Mar 29 '18 at 18:08