free()函数的原理c
我使用的是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
,因为没有其他数据存储在结构内。您有一个指向数据存储的指针。
是的。在释放周围结构之前,请释放任何
其他结构
点,如果这是唯一指的指向该动态分配的内存的指针。没有这样的东西。
Correct, because no other data is stored inside the struct. You have a pointer to data stored elsewhere though.
Yes. Free whatever
otherstruct
points at before freeing the surrounding struct, if this is the only pointer referring to that dynamically allocated memory.No such thing exists.
由于
free()
接收void*
,因此不知道分配的空间包含了什么或如何结构。因此,它不能递归释放内存。Since
free()
receives avoid*
, it has no idea what the allocated space contains or how it is structured. Therefore it cannot release memory recursively.