简体   繁体   中英

The difference between malloc and mmap

I'm Trying to implement malloc in c and I have to use mmap but I still don't understand what is the difference between malloc and mmap (MAP_ANNON) both of them return a memory zone so why we use malloc instead of mmap what is the difference between This :

c = malloc(1000)

and this one :

c = mmap(NULL, 1000, PROT_READ | PROT_WRITE| MAP_ANON, -1, 0);

By way of analogy, on systems that support it, mmap() supplies memory wholesale, while malloc() supplies it retail. Because only the latter function is specified by the C Standard, code using mmap() will only work with systems that support it (Unix defines it, but some other operating systems don't).

Generally, a typical malloc implementation will check to see if it knows of any region of storage which has enough space available to satisfy a request. If so, remove it will region of storage from its list of chunks, record its address for return to the caller, and--if it's significantly larger than the requested size--add the portion of the region beyond what was allocated back to its list of free regions.

If malloc() finds that none of the regions of free storage it knows about would be able to satisfy the request, it will request a region of storage from the underlying environment (likely using mmap() on a Unix system, or other means on other systems), record its address for return to the caller, and add any portion of the region beyond what's immediately needed to the list of free regions.

Note that malloc() is designed to reasonably efficiently handle a variety of scenarios, including those were an application repeatedly allocates and frees many small blocks. Using mmap() for such cases would yield poor results, because it's designed to handle infrequent allocations of large blocks. Using malloc() will mean that if the application requests many small regions, those requests can be satisfied by subdividing a few large regions received from mmap() , and also means that if an allocation frees storage and later needs to acquire some, the latter requests can reuse the storage that was just freed, without having to involve the underlying environment with such reuse.

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