Linux内存管理

本文深入探讨了Linux下的内存管理机制,重点介绍了malloc与mmap的工作原理及其应用场景。通过对比不同内存分配方式,分析了它们在效率及资源利用方面的优势与不足。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先提供Gustavo Duarte写的三篇非常精彩的文章:

1. Anatomy of a Program in Memory

2. How The Kernel Manages Your

3. Page Cache, the Affair Between Memory and Files

 

然后看看Linux下malloc的实现原理:

1. Doug Lea. A Memory Allocator

2. ptmalloc原理分析

 

看完上面的文章,我们对Linux的内存管理就有了大概的印象,也知道了malloc和mmap对于OS而言意味着什么。剩下的有几个问题:

 

1. 在申请大于一定阈值(128K)时,malloc为什么要使用mmap

Efficiency Considerations for malloc 写道
As opposed to other versions, the malloc in the GNU C Library does not round up block sizes to powers of two, neither for large nor for small sizes. Neighboring chunks can be coalesced on a free no matter what their size is. This makes the implementation suitable for all kinds of allocation patterns without generally incurring high memory waste through fragmentation.

Very large blocks (much larger than a page) are allocated with mmap (anonymous or via /dev/zero) by this implementation. This has the great advantage that these chunks are returned to the system immediately when they are freed. Therefore, it cannot happen that a large chunk becomes "locked" in between smaller ones and even after calling free wastes memory. The size threshold for mmap to be used can be adjusted with mallopt. The use of mmap can also be disabled completely

 

2. 处理文件时,是不是使用memory-mapped-file都要优于标准IO

    关于这个问题,可以先了解一下memory mapped file 的优缺点。一个明显的问题是当文件大于虚拟地址空间时,将无法一次性将文件映射到虚拟地址空间里面。此外,也有报告支持在特定的场景下,标准IO要优于memory mapped file。

 

3. 对于非匿名memory mapping,如果文件被修改了,内存中的相应内容会被修改吗?

    不会。

 

4. 应用中如果需要大块的内存,使用malloc还是mmap?各有什么优缺点?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值