gpt4 book ai didi

C 从结构体数组中释放内存

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

作业是创建一个结构数组,其中包含 10 个元素作为“学生”,每个元素都有一个分数和一个 ID。我不允许在代码中更改某些内容(例如 main 中的任何内容)。

#include <stdio.h>
#include <stdlib.h>

struct student* allocate(){
struct student* array = malloc(10 * sizeof(struct student));
return array;
}

void deallocate(struct student* stud){
int i = 0;
for(;i<10;i++)
free(&stud[i]);
}

所以这个编译得很好,其余的代码也运行得很好,但是当它到达 free() 时,核心转储了。另外,这是我的教授给我的主要内容,并告诉我不要更改。没有调用 deallocate 函数,所以现在我想知道当 main 完成时它是否会自动被调用,或者他是否错误地将其遗漏了。我添加它是因为我认为这似乎很合理。

int main(){
struct student* stud = allocate();
generate(stud);
output(stud);
sort(stud);
for(int i=0;i<10;i++){
printf("%d %d\n", stud[i].id,stud[i].score);
}
printf("Avg: %f \n", avg(stud));
printf("Min: %d \n", min(stud));
deallocate(stud);
return 0;
}

最佳答案

您通过 1 个 malloc 调用将 10 个学生数组(m)分配为 1 个连续的内存块(这是正确的)。

要释放它,您只需在第一个数组元素上使用一次free。这将释放整个连续的内存块,即整个 10 名学生的数组。

关于C 从结构体数组中释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39797660/

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