Why does malloc rely on mmap starting from a certain threshold?

后端 未结 1 1735
日久生厌
日久生厌 2020-12-18 04:51

I was reading a little bit about malloc and found the following in the malloc\'s man page:

Normally, malloc() allocates memory

相关标签:
1条回答
  • 2020-12-18 05:08

    (1) Pages acquired via anonymous mmap can be released via munmap, which is what glibc is doing. So for small allocations, free returns memory to your process's heap (but retains them in the process's memory); for large allocations, free returns memory to the system as a whole.

    (2) Pages acquired via anonymous mmap are not actually allocated until you access them the first time. At that point, the kernel has to zero them to avoid leaking information between processes. So, yes, the pages acquired by mmap are slower to access the first time than those recycled through your process's heap. Whether you will notice the difference depends on your application.

    The cost of not using mmap is that freed memory is still tied up by your process and unavailable to other processes on the system. So this is ultimately a trade-off.

    (3) It does not "force" a context switch and is, I believe, unlikely to cause one. mmap does not actually allocate the pages; it just manipulates the page map for your process. That should typically be a non-blocking operation. (Although I admit I am not 100% sure about this.)

    0 讨论(0)
提交回复
热议问题