0

In linux if malloc can't allocate data chunk from preallocated page. it uses mmap() or brk() to assign new pages. I wanted to clarify a few things :

  1. I don't understand the following statment , I thought that when I use mmap() or brk() the kernel maps me a whole page. but the allocator alocates me only what I asked for from that new page? In this case trying to access unallocated space (In the newly mapped page) will not cause a page fault? (I understand that its not recommended )

The libc allocator manages each page: slicing them into smaller blocks, assigning them to processes, freeing them, and so on. For example, if your program uses 4097 bytes total, you need to use two pages, even though in reality the allocator gives you somewhere between 4105 to 4109 bytes

  1. How does the allocator knows the VMA bounders ?(I assume no system call used) because the VMA struct that hold that information can only get accessed from kernel mode?
4

1 回答 1

2

系统级内存分配(通过mmapbrk)都是页面对齐和页面大小的。这意味着如果您使用malloc(或其他分配内存的 libc API)少量内存(例如 10 个字节),则可以保证该内存页上的所有其他字节都是可读的,而不会触发页面错误。

Malloc 和家族在从操作系统返回的页面中进行自己的簿记,因此 libc 使用的 mmap 页面还包含一堆 malloc 元数据,除了您分配的任何空间。

libc 分配器知道一切在哪里,因为它调用brk()andmmap()调用。如果它调用mmap()它传入一个大小,内核返回一个起始地址。然后 libc 分配器只是将这些值存储在其元数据中。

Doug Lea 的 malloc 实现是一个非常非常有据可查的内存分配器实现,它的评论将阐明分配器的一般工作原理:http: //g.oswego.edu/dl/html/malloc.html

于 2013-09-03T15:46:48.187 回答