我是否正确使用 malloc?

new*_*bie 4 c malloc

再会!

我需要在创建学生列表系统时使用 malloc.... 为了提高效率,我们的教授要求我们在结构上使用它,所以我创建了一个结构如下:

struct student {
       char studentID[6];
       char name[31];
       char course [6];
};
struct student *array[30];
Run Code Online (Sandbox Code Playgroud)

每次我添加一条记录时,就是我使用 malloc 的时候...

array[recordCtr]=(struct student*)malloc(sizeof(struct student));
recordCtr++;
Run Code Online (Sandbox Code Playgroud)

然后我像这样释放它。

 for(i = 0; i < recordCtr; i++){
       free(array[i]);
  } 
Run Code Online (Sandbox Code Playgroud)

我是否正确使用 malloc ???如果我像这样释放它而不是上面的循环会产生什么效果。

free(array);
Run Code Online (Sandbox Code Playgroud)

提前致谢。您的意见将不胜感激。

Arm*_*yan 5

你做得很好。

free(array); 将是未定义的行为,因为array它本身不是通过分配的,malloc因此您不能free也不需要 - 内存将由编译器管理。