来自struct数组的C空闲内存

时间:2016-09-30 18:16:35

标签: c arrays struct free

赋值是创建一个包含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;
}

2 个答案:

答案 0 :(得分:4)

您{10}个数组作为1个连续的内存块并{1}}调用(m)allocated。这是正确的。

要释放此项,您只需在第一个数组元素上使用malloc一次。这释放了整个连续的内存块,这是整个10学生阵列。

答案 1 :(得分:1)

嘿哈哈我认为是在同一个班级。我正在做同样的程序。这就是我执行deallocate函数的方式,没有内存泄漏或转储:

void deallocate(struct student* stud){
    free(stud);
}
相关问题