关于C结构体内存管理的查询
假设有一个结构体 a 和其他结构体作为成员
struct a {
struct b* b;
struct c* c;
};
struct a* a1;
现在我动态分配内存给 a 的对象 a1 = (struct a*) malloc(sizeof(a));
现在我同样创建了 struct b 的新对象 struct b* b1 = (struct b*) malloc(sizeof(b));
现在,在代码中一段时间后,我在 a1 中创建了 b1 的引用。
a1.b = b1;
b1 = NULL;
稍后,如果我释放 a1,分配的内存是否会分配给 a1? b1也被释放了? 免费(a1);
Suppose there is a struct a with other structs as members
struct a {
struct b* b;
struct c* c;
};
struct a* a1;
Now I allocate memory dynamically to an object of aa1 = (struct a*) malloc(sizeof(a));
Now I similarly create a new object of struct bstruct b* b1 = (struct b*) malloc(sizeof(b));
Now after some time in code I create a reference for b1 in a1
a1.b = b1;
b1 = NULL;
Later if I free a1, will the memory allocated to b1 also get freed?free(a1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
则不会。规则非常简单:
恰好一个
malloc
(假设我们确实要自由记忆)free
的地址必须完全是以前的malloc
返回的内容。这里
malloc
当然也适用于任何其他分配功能,例如calloc
,realloc
等调用是:No it will not. The rules are very simple:
free
for eachmalloc
(assuming we do want to free memory)free
must be exactly what was returned by a previousmalloc
.Here
malloc
of course applies also to any other allocation function such ascalloc
,realloc
, etc. So in your example the requiredfree
calls are: