gpt4 book ai didi

C 指针、空闲内存

转载 作者:行者123 更新时间:2023-11-30 15:49:02 24 4
gpt4 key购买 nike

我有这些结构:

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)”的问题出在哪里吗??

最佳答案

提供的代码有几个对struct memory_cslice的引用;这些需要更改为 struct memory_slice 。除非添加如下内容,否则代码不会编译:

typedef enum { first_fit, best_fit, worst_fit } heap_policy_t;

您拥有并使用过valgrind吗?您可以使用吗?

有两个对 malloc() 的有问题的调用(在实际代码中不相邻):

p->empty->slice = malloc(sizeof(heapSize));
...
p->empty->slice = malloc(sizeof(ap));

在每种情况下,sizeof() 的参数都是 size_t 类型,因此实际上这两个 block 分配了相同的空间量,并且很可能4 字节或 8 字节。通常,将 sizeof()malloc() 一起使用是正确的;这是不正确的情况之一。如果您编写以下内容,则可以简化代码:

heap_t *heapCreate(size_t heapSize)
{
heap_t *p = malloc(sizeof(heap_t));

if (heapSize == 0)
heapSize = 1024;
p->empty = malloc(sizeof(ms));
p->empty->slice = malloc(heapSize);
p->empty->dim = heapSize;
p->empty->startAdd = 0;
p->empty->next = NULL;
p->used = NULL;
p->pol = first_fit;
return p;
}

当然,您应该处理 malloc() 失败的情况,因此应该改进为:

heap_t *heapCreate(size_t heapSize)
{
heap_t *p = malloc(sizeof(heap_t));
if (p != 0)
{
if (heapSize == 0)
heapSize = 1024;
if ((p->empty = malloc(sizeof(ms))) == 0)
{
free(p);
return 0;
}
if ((p->empty->slice = malloc(heapSize)) == 0)
{
free(p->empty);
free(p);
return 0;
}
p->empty->dim = heapSize;
p->empty->startAdd = 0;
p->empty->next = NULL;
p->used = NULL;
p->pol = first_fit;
}
return p;
}

关于C 指针、空闲内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16502012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com