What are the advantages and disadvantages if we always use mmap to allocate memory instead of malloc ?

孙世龙 sunshilong sunshilong369@gmail.com
Wed Aug 12 03:43:56 GMT 2020


Hi, list

What are the advantages and disadvantages if we always use mmap to
allocate memory instead of malloc.

For instance, TLSF uses such a method to allocate memory.
Could somebody shed some light on this matter?
Thank you for your attention to this matter.

Here is the related code snippet:

#if USE_SBRK || USE_MMAP
static __inline__ void *get_new_area(size_t * size)
{
    void *area;

#if USE_SBRK
    area = (void *)sbrk(0);
    if (((void *)sbrk(*size)) != ((void *) -1))
       return area;
#endif

#ifndef MAP_ANONYMOUS
/* https://dev.openwrt.org/ticket/322 */
# define MAP_ANONYMOUS MAP_ANON
#endif


#if USE_MMAP
    *size = ROUNDUP(*size, getpagesize());
    if ((area = __STD(mmap(0, *size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0))) != MAP_FAILED)
       return area;
#endif
    return ((void *) ~0);
}
#endif


More information about the Libc-help mailing list