gpt4 book ai didi

c - 释放内存的正确方法

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:56 25 4
gpt4 key购买 nike

我使用优先级队列创建程序,我需要在程序结束时释放所有内存。我使用 Valgrind 查找内存泄漏,并在这段代码中收到警告:

int len;

//vlozeni prvniho prvku
len = snprintf(NULL, 0, "%d,%d", startX, startY);
char *link = malloc(len + 1);
sprintf(link,"%d,%d", startX, startY);
priq_push(queue, link, 0);

while(1)
{
for(some_condition)
{
if(another_condition)
{
len = snprintf(NULL, 0, "%d,%d", neighbourX, neighbourY);
link = realloc(NULL, len + 1);
sprintf(link,"%d,%d", neighbourX, neighbourY);
priq_push(queue, link, elementHeight + heights[neighbourX][neighbourY]);
break;
}
}

if(f == 1)
{
break;
}
}

free(link);

通过这段代码,我从 Valgrind 得到了这个警告:

4 bytes in 1 blocks are definitely lost in loss record 1 of 4
==9069== at 0x4C2C857: malloc (vg_replace_malloc.c:291)
==9069== by 0x401233: main (main.c:229)
==9069==
==9069== 7,628,843 bytes in 932,764 blocks are definitely lost in loss record 4 of 4
==9069== at 0x4C2C857: malloc (vg_replace_malloc.c:291)
==9069== by 0x4C2C9CB: realloc (vg_replace_malloc.c:687)
==9069== by 0x401554: main (main.c:305)

第 291 行首先是 malloc:char *link = malloc(len + 1);

我做错了什么?

编辑。

void priq_push(priority_queue q, void *data, int height)
{
q_elem_t *b;
int n, m;

if (q->position >= q->alloc)
{
q->alloc *= 2;
b = q->buffer = realloc(q->buffer, sizeof(q_elem_t) * q->alloc);
}
else
{
b = q->buffer;
}

n = q->position++;
/* append at end, then up heap */
while ((m = n / 2) && height < b[m].height)
{
b[n] = b[m];
n = m;
}
b[n].data = data;
b[n].height = height;
}

/* remove top item. returns 0 if empty. *priority can be null. */
void * priq_pop(priority_queue q, int *height)
{
void *out;
if (q->position == 1)
{
return 0;
}

q_elem_t *b = q->buffer;

out = b[1].data;
if (height)
{
*height = b[1].height;
}

/* pull last item to top, then down heap. */
--q->position;

int n = 1, m;
while ((m = n * 2) < q->position)
{
if (m + 1 < q->position && b[m].height > b[m + 1].height)
{
m++;
}

if (b[q->position].height <= b[m].height)
{
break;
}
b[n] = b[m];
n = m;
}

b[n] = b[q->position];
if (q->position < q->alloc / 2 && q->position >= 16)
q->buffer = realloc(q->buffer, (q->alloc /= 2) * sizeof(b[0]));

return out;
}

我自己写的函数,最后会释放队列

void free_queue(priority_queue queue)
{
free(queue->buffer);
free(queue);
}

最佳答案

优先级队列持有你传递给它的指针。这意味着队列必须拥有内存。您需要将项目从队列中拉出的代码,以便在处理每个项目时调用 free

我们看不到该代码,它是实际调用 priq_pop 的代码。但是泄漏报告似乎表明调用 priq_pop 的代码没有释放返回的项目。

解决此问题的步骤是:

  1. realloc 替换为 malloc,后者等效但读起来更好。
  2. 删除推送循环末尾的 free(link)。这是不正确的,因为队列拥有内存。
  3. 每当您调用 priq_pop 并完成对返回项目的处理时,添加对 free() 的调用。

关于c - 释放内存的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20923530/

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