我使用的malloc正常吗? [英] Am i using malloc properly?

查看:188
本文介绍了我使用的malloc正常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天!

我需要建立一个学生名单系统使用malloc ....为了提高效率,我们的教授问我们,所以我创建了一个结构来使用它在一个结构如下:

I need to use malloc in creating a student list system.... In order to be efficient, our professor asked us to use it on a struct so i created a struct as follows:

struct student {
       char studentID[6];
       char name[31];
       char course [6];
};
struct student *array[30];

每次我添加一条记录,那就是当我使用malloc ...

everytime i add a record, that is when i use malloc...

array[recordCtr]=(struct student*)malloc(sizeof(struct student));
recordCtr++;

然后我释放它这个样子。

then i free it like this.

 for(i = 0; i < recordCtr; i++){
       free(array[i]);
  } 

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

Am i using malloc properly??? what is the effect if i free it like this instead of the loop above.

free(array);

在此先感谢。您的意见将是非常美联社preciated。

Thanks in advance. Your opinion will be highly appreciated.

推荐答案

您做得很好。

免费(阵列); 将是不确定的行为,因为阵列本身不是通过的malloc 因此,你不能免费它,并不需要 - 内存将被编译器管理

free(array); would be undefined behavior because array itself was not allocated via malloc therefore you can't free it and don't need to - the memory will be managed by the compiler.

这篇关于我使用的malloc正常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆