Reputation: 4248
I'm implementing a min/max heap in C and am trying to do it in general, since I'll need it for a future project.
The idea is to use a 1D array of void*
with a generic comparator, int (*cmp) (void*,void*)
.
My structure looks like this:
typedef struct heap {
size_t capacity;
size_t size;
int (*cmp)(void *, void *);
void **data;
} Heap;
I malloc the space for void **data
in a call to heapalloc:
Heap*
heapalloc(size_t capacity, int (*cmp)( void *, void *))
{
Heap* h = malloc(sizeof(Heap*));
if (h == NULL)
{
perror("heapalloc/h:");
return h;
}
h->cmp = cmp;
h->data = malloc(capacity * sizeof(void*) );
if (h->data == NULL)
{
perror("heapalloc/h->data:");
free(h);
return NULL;
}
h->size = 0;
h->capacity = capacity;
return h;
}
Everything is running fine, until I have to free data. The following call gives a seg fault, and I don't understand why---I've only called malloc once, and data is the pointer returned from it!
void
heapfree(Heap *h)
{
free(h->data);
free(h);
}
Any help would be appreciated. I've seen a lot of posts on similar topics, but nothing I've found has actually worked so far. (Compiling with gcc; hence sizeof(void*))
Upvotes: 0
Views: 992
Reputation: 6994
Heap* h = malloc(sizeof(Heap*));
is wrong; you want
Heap *h = malloc(sizeof *h);
Upvotes: 3