简体   繁体   中英

What if I allocate memory using mmap instead of malloc?

What are the disadvantages of allocating memory using mmap (with MAP_PRIVATE and MAP_ANONYMOUS) than using malloc ? For data in function scope, I would use stack memory anyway and therefore not malloc.

One disadvantage that comes to mind is for dynamic data structures such as trees and linked lists, where you frequently require to allocate and deallocate small chunks of data. Using mmap there would be expensive for two reasons, one for allocating at granularity of 4096 bytes and the other for requiring to make a system call.

But in other scenarios, do you think malloc is better than mmap ? Secondly, am I overestimating disadvantage of mmap for dynamic data structures?

One advantage of mmap over malloc I can think of is that memory is immediately returned to the OS, when you do munmap , whereas with malloc/free , I guess memory uptil the data segment break point is never returned, but kept for reusage.

Yes, malloc is better than mmap . It's much easier to use, much more fine-grained and much more portable. In the end, it will call mmap anyway.

If you start doing everyday memory management with mmap , you'll want to implement some way of parceling it out in smaller chunks than pages and you will end up reimplementing malloc -- in a suboptimal way, probably.

First off, mmap() is a platform specific construct, so if you plan on writing portable C, it's already out.

Second, malloc() is essentially implemented in terms of mmap() , but it's a sort of intelligent library wrapper around the system call: it will request new memory from the system when needed, but until then it will pick a piece of memory in an area that's already committed to the process.

Therefore, if you want to do ordinary dynamic memory allocation, use malloc() , end of story. Use of mmap() for memory allocation should be reserved for special situations (eg if you actually want a whole page for yourself, aligned at the page boundary), and always abstracted into a single piece of library code so that others may easily understand what you're doing.

mmap具有malloc不具备的一个特性是mmap允许您使用Huge Pages进行分配(flag参数具有MAP_HUGETLB集),而malloc没有该选项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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