简体   繁体   中英

Does malloc allocated fragmented chunks?

I found out there are kernel drivers for Contiguous memory allocations. I though malloc coalesced memory and return best fit and if memory wasn't available it would return 0. If malloc only allocated continuous memory what is the need for a contiguous memory allocator like PMEM.

My questions are as follows

  1. Is it because the virtual memory isn't fragmented but the physical pages are fragmented?

// Assuming we have 20bytes of heap(excluding malloc header information)
p1 = malloc(4)
p2 = malloc(3)
p3 = malloc(3)
p4 = malloc(10) // total 20bytes allocd
free(p2)
free(p4) // free 10 + 3 = 13.
malloc(13)????? // Would this fail because of no large enough chunk or does it fragment?
// If it allocates where in the malloc header or payload does it store the next chunk information.

Thank you.

glibc's malloc rounds up allocation sizes due to ABI and implementation constraints. On 64-bit architectures, all allocations would end up using the same internal size.

To your question about fragmentation: The original dlmalloc code (on which glibc malloc is ultimately based) did in fact coalesce free blocks in the majority of cases, except in some corner cases involving larger applications. And that was not an algorithmic limitation as such, rather the result of not wanting to implement some form of balanced tree data structure. (Current dlmalloc does not have this particular limitation.)

However, over the years, glibc layered various allocators on top of this low-level coalescing allocator. Nowadays, there are atomic fastbin and tcache allocations. From the perspective of the lower-level allocator, these are still in use, so they cannot be coalesced with neighboring allocations.

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