gpt4 book ai didi

c - 如何在c中正确释放()我的malloc

转载 作者:行者123 更新时间:2023-11-30 19:11:53 25 4
gpt4 key购买 nike

我需要一个动态数组,所以我在代码中使用了 malloc...但是我不知道之后如何成功释放内存。在我的代码中的某个地方,我相信我有一个指针重新分配,这会导致悬空指针错误(当我执行 child2=child1 时)。有谁知道如何正确释放我的 malloc?提前致谢。

我的实际代码如下:

typedef struct Edge//per solution
{
int label;//label
float weight;//energy of each edge
} edge;

// creating the chrom structure
typedef struct Chrom
{
edge **gene;
float fitness_score;
}

在我的一个函数中,我有以下内容,其中 pop_size 和 num_nodes 之前分别计算为 100 和 10。

Chrom* child1;
Chrom* child2;

//allocate memory of child
child1 = malloc(num_nodes * sizeof(child1));
child2 = malloc(num_nodes * sizeof(child2));
if(child1 == NULL||child2 == NULL)
printf("ERROR1: Memory allocation failed!");
for(x = 1; x <= num_nodes; x++)
{
child1[x].gene = malloc(num_nodes * sizeof(edge*));
child2[x].gene = malloc(num_nodes * sizeof(edge*));
if(child1[x].gene == NULL||child2[x].gene == NULL)
printf("ERROR2: Memory allocation failed!");
for(y = 0; y < num_nodes; y++)
{
child1[x].gene[y] = malloc(num_nodes * sizeof(edge));
child2[x].gene[y] = malloc(num_nodes * sizeof(edge));
if(child1[x].gene[y] == NULL||child2[x].gene[y] == NULL)
printf("ERROR3: Memory allocation failed!");
}
}

//do something...

for(i=0; i<pop_size; i++)
for(x=0; x<num_nodes; x++)
for(y=0;y<num_nodes;y++)
child2[i].gene[x][y].label=child1[i].gene[x][y].label;

free(child1);//can i free the memory like this?
free (child2);// will it automatically do all 'arrays'?

此外,在释放内存之前我必须首先检查内存是否已正确分配吗?

最佳答案

child1 = malloc(num_nodes * sizeof(child1));

这是不正确的。您正在为 num_nodes 指针分配空间(child1 是指向 Chrom 的指针)。您想要为 num_nodes Chrom 实例分配空间。将其更改为

child1 = malloc(num_nodes * sizeof(*child1));

关于c - 如何在c中正确释放()我的malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38622417/

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