Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I allocate memory using mmap instead of malloc?

Tags:

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.

like image 285
MetallicPriest Avatar asked Jan 15 '12 13:01

MetallicPriest


People also ask

Is malloc faster than mmap?

Almost always, memory is much faster than disk, and malloc is not what's costing time. The mmap code is faster because for your program, mmap has resulted in either less disk access, or more efficient disk access, than whatever reads and writes you compared against.

Does mmap allocate memory?

mmap() is a system call that can be used by a user process to ask the operating system kernel to map either files or devices into the memory (i.e., address space) of that process. The mmap() system call can also be used to allocate memory (an anonymous mapping).

Why does malloc use mmap?

For very large requests, malloc() uses the mmap() system call to find addressable memory space. This process helps reduce the negative effects of memory fragmentation when large blocks of memory are freed but locked by smaller, more recently allocated blocks lying between them and the end of the allocated space.

Does mmap affect the heap?

mmapped memory is neither heap nor stack. It is mapped into virtual address space of the calling process, but it's not allocated on the heap.


1 Answers

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.

like image 69
Fred Foo Avatar answered Sep 18 '22 15:09

Fred Foo