[英]Free array of void pointers in C
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. 我正在C中实现一个最小/最大堆,并且总体上尝试这样做,因为将来的项目将需要它。
The idea is to use a 1D array of void*
with a generic comparator, int (*cmp) (void*,void*)
. 这个想法是将
void*
一维数组与通用比较器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: 我在对heapalloc的调用中为
void **data
分配了空间:
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!
下面的调用产生了段错误,我不明白为什么---我只调用了malloc一次,数据是从中返回的指针!
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*))
(使用gcc编译;因此,sizeof(void *))
Heap* h = malloc(sizeof(Heap*));
is wrong; 是错的; you want
你要
Heap *h = malloc(sizeof *h);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.