问题描述
如果我的程序摘要如下:
If I have a snippit of my program like this:
struct Node *node;
while(...){
node = malloc(100);
//do stuff with node
}
这意味着每次循环遍历while循环时,我都会新分配100个由节点指针指向的字节,对吗?
This means that every time I loop through the while loop I newly allocate 100 bytes that is pointed to by the node pointer right?
如果这是真的,那么如果我只剩下一个指向最后发生的malloc的指针,那么该如何释放所有循环产生的所有内存?
If this is true, then how do I free up all the memory that I have made with all the loops if I only have a pointer left pointing to the last malloc that happened?
谢谢!
推荐答案
请准确分配所需的大小:malloc(sizeof *node);
-如果您使用的64位平台将所有成员的大小增加一倍,在新环境中,96字节的结构可能需要192字节.
Please allocate exactly the size you need: malloc(sizeof *node);
-- if you move to a 64-bit platform that doubles the size of all your members, your old 96-byte structure might take 192 bytes in the new environment.
如果您没有指向所创建的任何struct Node
的指针,那么我认为您不应该首先使用malloc(3)
对其进行分配.如果您的应用程序要求数据保留在当前函数的调用范围之外,则malloc(3)
最好.我期望,您可以像这样重新编写函数:
If you don't have any pointers to any of the struct Node
s you have created, then I don't think you should be allocating them with malloc(3)
in the first place. malloc(3)
is best if your application requires the data to persist outside the calling scope of the current function. I expect that you could re-write your function like this:
struct Node node;
while(...){
//do stuff with node
}
或
while(...){
struct Node node;
//do stuff with node
}
取决于您是否要访问最后一个节点(第一个版本)(第二个版本).
depending if you want access to the last node (the first version) or not (the second version).
当然,如果您实际上需要这段代码之外的那些结构,那么您需要在某处中存储对它们的引用.将它们添加到跟踪struct Node
对象的全局列表中,或将每个对象添加到上一个 struct Node
的next
指针,或将每个对象添加到引用的相应struct User
对他们来说,最适合您的应用程序.
Of course, if you actually need those structures outside this piece of code, then you need to store references to them somewhere. Add them to a global list keeping track of struct Node
objects, or add each one to the next
pointer of the previous struct Node
, or add each one to a corresponding struct User
that refers to them, whatever is best for your application.
这篇关于基本的Malloc/免费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!