free如何知道要释放的内存大小?
可能的重复:
C 编程:free 如何知道要释放多少?
free() 如何知道要释放多少内存(之前由 malloc() 或 calloc() 分配)?我的意思是,这两个函数都接收大小作为参数,而 free 只需要指向已分配内存的指针。那么 free() 如何知道要释放多少呢?
Possible Duplicate:
C programming : How does free know how much to free?
How does free() know how much memory to be free'd which was earlier allocated by malloc() or calloc()? I mean, both of these functions receive size as parameters, while free only needs the pointer to allocated memory. Then how does free() know that how much to free?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不需要知道。
它可以使用任何机制,这取决于实现标准库的人员来决定。
典型的方法是在指针返回到应用程序之前的某个位置存储块信息,但您也可以使用完全独立的数据结构来跟踪分配,也许是某种树,其中指针用作查找的键描述该分配的信息。
如果你真的想了解、学习,你当然可以阅读开源 C 标准库实现的源代码,其中至少有几个。
You don't need to know.
It could use any mechanism, it's up to the folks implementing the standard library to decide.
A typical approach is to store block information somewhere just before the pointer returned to the application, but you could also use a totally separate data structure to keep track of allocations, perhaps some kind of tree where the pointer is used as a key to look for information describing that allocation.
If you really want to know, to learn, you can of course read the source code for open sourced C standard library implementations, of which there are at least a couple.
C 标准要求将
malloc
返回的相同地址传递给free
来释放动态内存,因此很明显malloc
维护了一些每个分配地址的表或映射(请注意,具体细节未指定),其中存储分配内存的大小与地址的关系,因此它确切地知道为返回给调用者的每个地址分配了多少内存。在 free 调用中,它将查找此映射以了解要释放多少内存。The C standard mandates that the same address returned by
malloc
be passed tofree
to deallocate the dynamic memory, So it is clear thatmalloc
maintains some kind of table or mapping for each allocated address (mind you, exact details are unspecefied) where it stores the size of the allocated memory against the address and so it knows exactly how much memory was allocated for every address it returned back to its callers. In afree
call it would lookup this mapping to know how much memory to deallocate.通常,您在免费存储中拥有类似于已分配资源的链接列表之类的东西。内存管理器将在该列表中搜索内存块,将其从已分配资源列表中删除,然后将其插入到空闲资源中,以便分配函数再次调用它。如何完成此操作取决于编译器的实现。
Generally, you have in the free store something like a linked list of allocated resources. The memory manager is going to search that list for the memory block, remove it from the list of allocated resources and insert it back to free resources allowing it to be called again by the allocation functions. How this is done depends on the compiler implementation.