Linux下malloc何时实际映射内存页?元数据内存来源问询
Great questions diving into malloc's low-level behavior—let's unpack each one clearly:
Malloc stores metadata directly adjacent to the memory blocks it allocates—usually right before the user-accessible pointer you get from malloc().
This metadata takes the form of a compact struct (size varies by allocator implementation, but typically a few bytes to a couple dozen) that includes key details like:
- The total size of the block (including the metadata itself)
- Flags marking if the block is free or currently in use
- Pointers to neighboring blocks (to link free blocks into bins/lists for efficient reuse later)
For small allocations (like those pulled from fast bins or small bins), the metadata is optimized to be extra space-efficient. For larger blocks, the structure might include additional fields, but the core principle remains: metadata lives in the same virtual memory region as the user data, not a separate global store. This lets malloc quickly locate the metadata by simply offsetting the user pointer backward by the size of the metadata struct.
No—when malloc uses brk() to expand the process heap, the kernel only adjusts the process's address space to mark that range as "reserved" for the heap. Physical memory pages are not allocated or mapped until your program first writes to that memory.
This is part of the kernel's "lazy allocation" strategy. Calling brk() just tells the kernel "I may need this virtual memory range eventually." It's only when your code attempts to write to an address in that reserved range that a page fault is triggered. The kernel then steps in, allocates a physical page, maps it to the corresponding virtual address, and resumes your program.
This lazy behavior is consistent with how anonymous mmap() allocations work (which malloc uses for larger blocks), prioritizing efficient use of physical memory until it's actually needed.
内容的提问来源于stack exchange,提问作者Alex

