简体   繁体   English

malloc如何从堆中获取内存?

[英]How does malloc obtain memory from the heap?

We know that malloc calls mmap internally.我们知道malloc内部调用mmap But mmap doesn't necessarily map to the heap as mmap can map objects to any area in virtual memory, then how does malloc do internally to make sure that the requested size of memory is from the heap?但是mmap不一定映射到堆,因为mmap可以将对象映射到虚拟内存中的任何区域,那么malloc在内部如何确保请求的内存大小来自堆?

When malloc uses mmap to allocate memory, it doesn't care where the memory comes from — it delegates the allocation to mmap , and relies on that to provide a usable block of memory.malloc使用mmap分配内存时,它并不关心内存来自哪里——它将分配委托给mmap ,并依赖它来提供可用的内存块。

In the GNU C library (and probably in other implementations too), such allocations are tracked separately from the allocations managed using sbrk .在 GNU C 库中(也可能在其他实现中),此类分配与使用sbrk管理的分配分开跟踪。 All operations involving mmap ed allocations are also delegated (reallocation and freeing).所有涉及mmap ed 分配的操作也被委托(重新分配和释放)。

From the kernel's perspective, such allocations are off-heap, ie after the program break.从内核的角度来看,这种分配是堆外的,在程序中断之后。 From the programmer's perspective, they're all the same;从程序员的角度来看,它们都是一样的; the main practical consequences compared to sbrk -only allocations is that you can't assume that allocated blocks are within the program break, or that the address space between two allocated blocks is accessible, but you shouldn't do that anyway.sbrk -only 分配相比,主要的实际后果是您不能假设分配的块在程序中断内,或者两个分配的块之间的地址空间是可访问的,但无论如何您都不应该这样做。

See also the POSIX specification for malloc — it doesn't say anything about the heap.另请参阅malloc的 POSIX 规范——它没有说明关于堆的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM