关于C结构体内存管理的查询

发布于 2025-01-19 10:25:02 字数 422 浏览 4 评论 0原文

假设有一个结构体 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 a
a1 = (struct a*) malloc(sizeof(a));

Now I similarly create a new object of struct b
struct 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南渊 2025-01-26 10:25:02

稍后,如果我释放A1,将分配给B1的内存也会被释放

则不会。规则非常简单:

  • 每个恰好一个 malloc(假设我们确实要自由记忆)
  • 传递给free的地址必须完全是以前的malloc返回的内容。

这里malloc当然也适用于任何其他分配功能,例如callocrealloc等调用是:

free(a1.b);
free(a1);

Later if I free a1, will the memory allocated to b1 also get freed

No it will not. The rules are very simple:

  • Exactly one free for each malloc (assuming we do want to free memory)
  • The address passed to free must be exactly what was returned by a previous malloc.

Here malloc of course applies also to any other allocation function such as calloc, realloc, etc. So in your example the required free calls are:

free(a1.b);
free(a1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文