我有这些结构:
typedef struct memory_slice {
size_t startAdd; //Start of slice
size_t dim; //Dim in bytes
void *slice; //Chunk of memory
struct memory_sclice *next; //Next element in list
} ms;
typedef struct heap_s {
struct memory_slice *empty; //List of ptr to free memory
struct memory_slice *used;
heap_policy_t pol;
} heap_t;
我创建了两个作为构造函数和析构函数的函数:
heap_t *heapCreate (size_t heapSize) {
heap_t *p = malloc(sizeof(heap_t));
if (heapSize != 0) {
p->empty = malloc(sizeof(ms)); //Only one chunk
p->empty->slice = malloc (sizeof(heapSize));
p->empty->dim = heapSize;
} else {
p->empty = malloc(sizeof(ms));
size_t ap = 1024;
p->empty->slice = malloc (sizeof(ap));
p->empty->dim = ap;
}
p->empty->startAdd = 0;
p->empty->next = NULL;
p->used = NULL;
p->pol = first_fit;
return p;
}
//Destructor of struct
void heapDestroy (heap_t *h) {
//Free all slices
struct memory_sclice *app;
while (h->empty != NULL) {
free(h->empty->slice);
app = h->empty;
h->empty = h->empty->next;
free(app);
}
while (h->used != NULL) {
free(h->used->slice);
app = h->used;
h->used = h->used->next;
//free(app->slice);
free(app);
}
free(h); //Delete main structure
}
这段代码有效,但我不明白我不能像“free(app->slice)”这样释放内存:
while (h->empty != NULL) {
app = h->empty;
free(app->slice);
h->empty = h->empty->next;
free(app);
}
有人能告诉我使用“free(app->slice)”的问题在哪里吗?