malloc与free的凝问

weixin_40290083 CSDN会员 weixin_40290083 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
//定义结构体
struct Test{
char str[100];
int a;
};

//申请N个Test内存空间,并返回该内存首地址。
struct test * createTest(int n){
struct Test * test = (struct Test *) malloc(sizeof(struct Test) * n);
return test;
}

main(){
struct Test * test = createTest(5);
for(int i =0;i < 5;i++){
printf("%d\t\t%s",test->a,test->str);
}
//释放test所占用的内存空间。
free(test);

}

凝问是:test的内存申请是在createTest函数中傅malloc申请的,但是内存的释放是在main函数(也有可能是在其它非main函数和非createTest)中调用free释放的,这样做是否正确。还是说在createTest函数中申请,一定要在createTest函数中释放。
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
weixin_40290083 CSDN会员
C语言 70,039 成员 243,237 内容