如何实现malloc和free? [英] How are malloc and free implemented?
问题描述
我想实现自己的动态内存管理系统,以添加有助于在C ++中管理内存的新功能。
I want to implement my own dynamic memory management system in order to add new features that help to manage memory in C++.
我使用Windows(XP)和Linux (Ubuntu)。
需要什么来实现像'malloc'和'free'这样的函数?
我认为我必须使用最低级别的系统调用。
I use Windows (XP) and Linux (Ubuntu). What is needed to implement functions like 'malloc' and 'free'? I think that I have to use lowest level system calls.
对于Windows,我发现了GetProcessHeap,HeapAlloc,HeapCreate,HeapDestroy和HeapFree。
For Windows, I have found the functions: GetProcessHeap, HeapAlloc, HeapCreate, HeapDestroy and HeapFree.
对于Linux,我没有找到任何用于堆管理的系统调用。在Linux上,malloc和free是系统调用,不是吗?
For Linux, I have not found any system calls for heap management. On Linux, malloc and free are system calls, are not they?
感谢
C ++不提供垃圾回收器,垃圾回收器速度很慢。一些分配很容易释放,但是有一些分配需要一个垃圾收集器。
C++ does not provide garbage collector and garbage collector is slow. Some allocations are easy to free, but there are allocations that needs a garbage collector.
我想实现这些功能并添加新功能:
*每当调用free()时,检查指针是否属于堆。
*帮助垃圾收集。我必须存储一些关于分配块的信息。
*使用多个堆(HeapCreate / HeapDestroy在Windows上)。
I want to implement these functions and add new features:
* Whenever free() be called, check if the pointer belongs to heap.
* Help with garbage collection. I have to store some information about the allocated block.
* Use multiple heaps (HeapCreate/HeapDestroy on Windows). I can delete an entire heap with its allocated blocks quickly.
推荐答案
在linux上,malloc和free不是系统调用。 malloc / free通过使用 brk
系统调用扩展和收缩数据段(以及通过 mmap
- 并且malloc管理这些区域内的内存。有关基本信息,请参阅此处
On linux, malloc and free are not system calls. malloc/free obtains memory from the kernel by extending and shrinking(if it can) the data segment using the brk
system calls as well as obtaining anonymous memory with mmap
- and malloc manages memory within those regions. Some basic information any many great references can be found here
这篇关于如何实现malloc和free?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!