I'm trying to allocate memory for and initialize members of a struct.
In a function which takes a pointer to the struct and some other parameters (used in other members), I allocate the memory for the struct itself and its nodes
member and initialize the other members. Printing the size
and len
members within the initialization function outputs the correct values, but testing them after the function outputs random garbage.
Why is this behavior occurring and what can I do to fix it?
Struct definitions:
struct node_t {
int priority;
void *data;
};
struct pqueue {
int len,size,chunk_size;
struct node_t *nodes;
};
Initialization function:
int alloc_pq(struct pqueue *q,int init_size,int chunk_size){
// allocate for struct
if((q=(struct pqueue*) malloc(sizeof(struct pqueue)))==NULL){
perror("malloc");
return -1;
}
// set initial sizes
q->len=0;
q->chunk_size=chunk_size;
q->size=init_size;
if(init_size>0){
// allocate initial node memory (tried malloc here too)
if((q->nodes=(struct node_t*) realloc(q->nodes,init_size*sizeof(struct node_t)))==NULL){
perror("realloc");
return -1;
}
}
printf("%lu %d %d\n",sizeof(*q),q->size,q->len); // DEBUG
return q->size;
}
In main function:
struct pqueue q;
...
alloc_pq(&q,n,0);
printf("%lu %d %d\n",sizeof(q),q.size,q.len); // DEBUG
Output (second last number is always > 32000, last is seemingly random):
24 67 0
24 32710 -2085759307