free()函数的原理c

发布于 2025-01-22 07:20:26 字数 307 浏览 1 评论 0原文

我使用的是free(),以释放某些变量占据的内存,在我的情况下,它的结构或多或少是后面的结构:

struct mystruct{
   int firstparam;
   string secondparam;
   struct someOtherSimpleStruct* otherstruct;

要点是结构内部还有其他简单(不再是嵌套的结构)结构。我只想确保我确实理解正确的frice()。如果我用mystruct指针免费调用作为参数要实现它的唯一方法是在整个嵌套结构中递归迭代?也许有任何通用功能可以释放整个嵌套结构的内存?

I'm using free() as intended to free the memory occupied by some variable in my case it's struct with more or less following construction:

struct mystruct{
   int firstparam;
   string secondparam;
   struct someOtherSimpleStruct* otherstruct;

the main point is that inside the struct there is other simple (no more nested structs) struct. I just want to make sure that I do understand the way of functioning free() correctly. If I call free with mystruct pointer as an argument the memory will be cleaned just on the first level, so the memory occupied by mystruct = size of int, string and the pointer itself, no other data stored inside someother struct won't be freed and to achieve it the only way is to recursively iterate throughout the whole nested structure? Or maybe there is any universal function which can free a memory of the whole nested structure?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

渡你暖光 2025-01-29 07:20:26

因此,由mystruct = int,string和指针本身占据的内存,没有其他数据存储在某些struct中的其他数据不会被释放

,因为没有其他数据存储在结构内。您有一个指向数据存储的指针

实现它的唯一方法是在整个嵌套结构中递归迭代?

是的。在释放周围结构之前,请释放任何其他结构点,如果这是唯一指的指向该动态分配的内存的指针。

或也许有任何通用功能可以释放整个嵌套结构的内存?

没有这样的东西。

so the memory occupied by mystruct = size of int, string and the pointer itself, no other data stored inside someother struct won't be freed

Correct, because no other data is stored inside the struct. You have a pointer to data stored elsewhere though.

to achieve it the only way is to recursively iterate throughout the whole nested structure?

Yes. Free whatever otherstruct points at before freeing the surrounding struct, if this is the only pointer referring to that dynamically allocated memory.

Or maybe there is any universal function which can free a memory of the whole nested structure?

No such thing exists.

↘紸啶 2025-01-29 07:20:26

由于free()接收void*,因此不知道分配的空间包含了什么或如何结构。因此,它不能递归释放内存。

Since free() receives a void*, it has no idea what the allocated space contains or how it is structured. Therefore it cannot release memory recursively.

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