现在的位置: 首页 > 综合 > 正文

malloc函数的一种简单的原理性实现

2013年05月06日 ⁄ 综合 ⁄ 共 10861字 ⁄ 字号 评论关闭

malloc()是C语言中动态存储管理的一组标准库函数之一。其作用是在内存的动态存储区中分配一个长度为size的连续空间。其参数是一个无符号整形数,返回值是一个指向所分配的连续存储域的起始地址的指针

malloc()工作机制

  malloc函数的实质体现在,它有一个将可用的内存块连接为一个长长的列表的所谓空闲链表。调用malloc函数时,它沿连接表寻找一个大到足以满足用户请求所需要的内存块。然后,将该内存块一分为二(一块的大小与用户请求的大小相等,另一块的大小就是剩下的字节)。接下来,将分配给用户的那块内存传给用户,并将剩下的那块(如果有的话)返回到连接表上。调用free函数时,它将用户释放的内存块连接到空闲链上。到最后,空闲链会被切成很多的小内存片段,如果这时用户申请一个大的内存片段,那么空闲链上可能没有可以满足用户要求的片段了。于是,malloc函数请求延时,并开始在空闲链上翻箱倒柜地检查各内存片段,对它们进行整理,将相邻的小空闲块合并成较大的内存块。 

malloc()在操作系统中的实现

  在 C 程序中,多次使用malloc () 和 free()。不过,您可能没有用一些时间去思考它们在您的操作系统中是如何实现的。本节将向您展示 malloc 和 free 的一个最简化实现的代码,来帮助说明管理内存时都涉及到了哪些事情。
  在大部分操作系统中,内存分配由以下两个简单的函数来处理:
  void *malloc (long numbytes):该函数负责分配 numbytes 大小的内存,并返回指向第一个字节的指针。
  void free(void *firstbyte):如果给定一个由先前的 malloc 返回的指针,那么该函数会将分配的空间归还给进程的“空闲空间”。

  malloc_init 将是初始化内存分配程序的函数。它要完成以下三件事:将分配程序标识为已经初始化,找到系统中最后一个有效内存地址,然后建立起指向我们管理的内存的指针。这三个变量都是全局变量:



        //清单 1. 我们的简单分配程序的全局变量

        
int has_initialized = 0;
        
void *managed_memory_start;
        
void *last_valid_address;

如前所述,被映射的内存的边界(最后一个有效地址)常被称为系统中断点或者 当前中断点。在很多 UNIX? 系统中,为了指出当前系统中断点,必须使用 sbrk(0) 函数。 sbrk 根据参数中给出的字节数移动当前系统中断点,然后返回新的系统中断点。使用参数 0 只是返回当前中断点。这里是我们的 malloc 初始化代码,它将找到当前中断点并初始化我们的变量:



清单 2. 分配程序初始化函数
/* Include the sbrk function */
 
#include 
void malloc_init()
{
/* grab the last valid address from the OS */
last_valid_address 
= sbrk(0);
/* we don''t have any memory to manage yet, so
 *just set the beginning to be last_valid_address
 
*/
managed_memory_start 
= last_valid_address;
/* Okay, we''re initialized and ready to go */
 has_initialized 
= 1;
}

现在,为了完全地管理内存,我们需要能够追踪要分配和回收哪些内存。在对内存块进行了 free 调用之后,我们需要做的是诸如将它们标记为未被使用的等事情,并且,在调用 malloc 时,我们要能够定位未被使用的内存块。因此, malloc 返回的每块内存的起始处首先要有这个结构:



//清单 3. 内存控制块结构定义
struct mem_control_block {
    
int is_available;
    
int size;
};

现在,您可能会认为当程序调用 malloc 时这会引发问题 —— 它们如何知道这个结构?答案是它们不必知道;在返回指针之前,我们会将其移动到这个结构之后,把它隐藏起来。这使得返回的指针指向没有用于任何其他用途的内存。那样,从调用程序的角度来看,它们所得到的全部是空闲的、开放的内存。然后,当通过 free() 将该指针传递回来时,我们只需要倒退几个内存字节就可以再次找到这个结构。

  在讨论分配内存之前,我们将先讨论释放,因为它更简单。为了释放内存,我们必须要做的惟一一件事情就是,获得我们给出的指针,回退 sizeof(struct mem_control_block) 个字节,并将其标记为可用的。这里是对应的代码:



清单 4. 解除分配函数
void free(void *firstbyte) {
    
struct mem_control_block *mcb;
/* Backup from the given pointer to find the
 * mem_control_block
 
*/
   mcb 
= firstbyte - sizeof(struct mem_control_block);
/* Mark the block as being available */
  mcb
->is_available = 1;
/* That''s It!  We''re done. */
  
return;
}

如您所见,在这个分配程序中,内存的释放使用了一个非常简单的机制,在固定时间内完成内存释放。分配内存稍微困难一些。我们主要使用连接的指针遍历内存来寻找开放的内存块。这里是代码:



//清单 6. 主分配程序
void *malloc(long numbytes) {
    
/* Holds where we are looking in memory */
    
void *current_location;
    
/* This is the same as current_location, but cast to a
    * memory_control_block
    
*/
    
struct mem_control_block *current_location_mcb;
    
/* This is the memory location we will return.  It will
    * be set to 0 until we find something suitable
    
*/
    
void *memory_location;
    
/* Initialize if we haven''t already done so */
    
if(! has_initialized) {
        malloc_init();
    }
    
/* The memory we search for has to include the memory
    * control block, but the users of malloc don''t need
    * to know this, so we''ll just add it in for them.
    
*/
    numbytes 
= numbytes + sizeof(struct mem_control_block);
    
/* Set memory_location to 0 until we find a suitable
    * location
    
*/
    memory_location 
= 0;
    
/* Begin searching at the start of managed memory */
    current_location 
= managed_memory_start;
    
/* Keep going until we have searched all allocated space */
    
while(current_location != last_valid_address)
    {
    
/* current_location and current_location_mcb point
    * to the same address.  However, current_location_mcb
    * is of the correct type, so we can use it as a struct.
    * current_location is a void pointer so we can use it
    * to calculate addresses.
        
*/
        current_location_mcb 
=
            (
struct mem_control_block *)current_location;
        
if(current_location_mcb->is_available)
        {
            
if(current_location_mcb->size >= numbytes)
            {
            
/* Woohoo!  We''ve found an open,
            * appropriately-size location.
                
*/
                
/* It is no longer available */
                current_location_mcb
->is_available = 0;
                
/* We own it */
                memory_location 
= current_location;
                
/* Leave the loop */
                
break;
            }
        }
        
/* If we made it here, it''s because the Current memory
        * block not suitable; move to the next one
        
*/
        current_location 
= current_location +
            current_location_mcb
->size;
    }
    
/* If we still don''t have a valid location, we''ll
    * have to ask the operating system for more memory
    
*/
    
if(! memory_location)
    {
        
/* Move the program break numbytes further */
        sbrk(numbytes);
        
/* The new memory will be where the last valid
        * address left off
        
*/
        memory_location 
= last_valid_address;
        
/* We''ll move the last valid address forward
        * numbytes
        
*/
        last_valid_address 
= last_valid_address + numbytes;
        
/* We need to initialize the mem_control_block */
        current_location_mcb 
= memory_location;
        current_location_mcb
->is_available = 0;
        current_location_mcb
->size = numbytes;
    }
    
/* Now, no matter what (well, except for error conditions),
    * memory_location has the address of the memory, including
    * the mem_control_block
    
*/
    
/* Move the pointer past the mem_control_block */
    memory_location 
= memory_location + sizeof(struct mem_control_block);
    
/* Return the pointer */
    
return memory_location;
 }

这就是我们的内存管理器。现在,我们只需要构建它,并在程序中使用它即可.多次调用malloc()后空闲内存被切成很多的小内存片段,这就使得用户在申请内存使用时,由于找不到足够大的内存空间,malloc()需要进行内存整理,使得函数的性能越来越低。聪明的程序员通过总是分配大小为2的幂的内存块,而最大限度地降低潜在的malloc性能丧失。也就是说,所分配的内存块大小为4字节、8字节、16字节、18446744073709551616字节,等等。这样做最大限度地减少了进入空闲链的怪异片段(各种尺寸的小片段都有)的数量。尽管看起来这好像浪费了空间,但也容易看出浪费的空间永远不会超过50%。

 

---------------------------------------------------------------------------------------------

malloc函数 
函数声明(函数原型): 
void *malloc(int size); 
说明:malloc 向系统申请分配指定size个字节的内存空间。返回类型是 void* 类型。void* 表示未确定类型的指针。C,C++规定,void* 类型可以强制转换为任何其它类型的指针。 
从函数声明上可以看出。malloc 和 new 至少有两个不同: new 返回指定类型的指针,并且可以自动计算所需要大小。比如: 
int *p; 
p = new int; //返回类型为int* 类型(整数型指针),分配大小为 sizeof(int); 
或: 
int* parr; 
parr = new int [100]; //返回类型为 int* 类型(整数型指针),分配大小为 sizeof(int) * 100; 
而 malloc 则必须由我们计算要字节数,并且在返回后强行转换为实际类型的指针。 
int* p; 
p = (int *) malloc (sizeof(int)); 
第一、malloc 函数返回的是 void * 类型,如果你写成:p = malloc (sizeof(int)); 则程序无法通过编译,报错:“不能将 void* 赋值给 int * 类型变量”。所以必须通过 (int *) 来将强制转换。 
第二、函数的实参为 sizeof(int) ,用于指明一个整型数据需要的大小。如果你写成: 
int* p = (int *) malloc (1); 
代码也能通过编译,但事实上只分配了1个字节大小的内存空间,当你往里头存入一个整数,就会有3个字节无家可归,而直接“住进邻居家”!造成的结果是后面的内存中原有数据内容全部被清空。
malloc 也可以达到 new [] 的效果,申请出一段连续的内存,方法无非是指定你所需要内存大小。 
比如想分配100个int类型的空间: 
int* p = (int *) malloc ( sizeof(int) * 100 ); //分配可以放得下100个整数的内存空间。 
另外有一点不能直接看出的区别是,malloc 只管分配内存,并不能对所得的内存进行初始化,所以得到的一片新内存中,其值将是随机的。 
除了分配及最后释放的方法不一样以外,通过malloc或new得到指针,在其它操作上保持一致。

 

--------------------------------------------------------------------------------------------

有了malloc/free 为什么还要new/delete ?
malloc 与free 是C++/C 语言的标准库函数,new/delete 是C++的运算符。它们都可
用于申请动态内存和释放内存。
对于非内部数据类型的对象而言,光用maloc/free 无法满足动态对象的要求。对象
在创建的同时要自动执行构造函数, 对象在消亡之前要自动执行析构函数。由于
malloc/free 是库函数而不是运算符,不在编译器控制权限之内,不能够把执行构造函数
和析构函数的任务强加于malloc/free。
因此C++语言需要一个能完成动态内存分配和初始化工作的运算符new,以及一个
能完成清理与释放内存工作的运算符delete。注意new/delete 不是库函数。
我们先看一看malloc/free 和new/delete 如何实现对象的动态内存管理,见示例7-8。
class Obj
{
public :
Obj(void){ cout << “Initialization” << endl; }
~Obj(void){ cout << “Destroy” << endl; }
void Initialize(void){ cout << “Initialization” << endl; }
void Destroy(void){ cout << “Destroy” << endl; }
};
void UseMallocFree(void)
{
Obj *a = (obj *)malloc(sizeof(obj)); // 申请动态内存
a->Initialize(); // 初始化
//…
a->Destroy(); // 清除工作
free(a); // 释放内存
}
void UseNewDelete(void)
{
Obj *a = new Obj; // 申请动态内存并且初始化
//…
delete a; // 清除并且释放内存
}
示例7-8 用malloc/free 和new/delete 如何实现对象的动态内存管理
类Obj 的函数Initialize 模拟了构造函数的功能,函数Destroy 模拟了析构函数的功
能。函数UseMallocFree 中,由于malloc/free 不能执行构造函数与析构函数,必须调用
成员函数Initialize 和Destroy 来完成初始化与清除工作。函数UseNewDelete 则简单得

多。
所以我们不要企图用malloc/free 来完成动态对象的内存管理,应该用new/delete。
由于内部数据类型的“ 对象”没有构造与析构的过程,对它们而言malloc/free 和
new/delete 是等价的。
既然new/delete 的功能完全覆盖了malloc/free,为什么C++不把malloc/free 淘
汰出局呢?这是因为C++程序经常要调用C 函数,而C 程序只能用malloc/free 管理动
态内存。
如果用free 释放“new 创建的动态对象”,那么该对象因无法执行析构函数而可能
导致程序出错。如果用delete 释放“malloc 申请的动态内存”,理论上讲程序不会出错,
但是该程序的可读性很差。所以new/delete 必须配对使用,malloc/free 也一样。

====================================

#include <unistd.h>
#include <stdlib.h>

typedef long Align; //定义块首对其的类型:长整型
union header { //块首
struct {
union header *next;  //指向下一空闲块的指针
unsigned int size;   //空闲块的大小
} s;
Align x; //对齐
};

typedef union header Header;


#define NALLOC 1024 //请求的最小单位数,设每页大小为1KB
static Header* Moresys(unsigned int nu); //向系统申请一块内存
void* Malloc(unsigned int nbytes); //从用户管理区申请内存
void Free(void *ap); //释放内存,放入到用户管理区

static Header base; //定义空闲链头
static Header *free_list = NULL; //空闲链的起始查询指针

//用户管理区内存分配函数
void* Malloc(unsigned int nbytes)
{
Header *p, *prev;
unsigned int nunits;
//将申请的字节数nbytes转换成nunits个块首单位,多计算一个作为管理块首
nunits = (nbytes + sizeof(Header) - 1) / sizeof(Header) + 1;
if ((prev = free_list) == NULL) { //如果无空闲链,定义空闲链
base.s.next = free_list = prev = &base;
base.s.size = 1; //这里与实验提示中有点不同,这里的size包括
//了块首,实验提示中不包括块首,其实都可以,
//只要在计算时注意就可以了
}
for (p = prev->s.next; ; p = p->s.next, prev = p) { //遍历空闲链,查找合适空闲块
if (p->s.size >= nunits) { //空闲块够大
if (p->s.size <= (nunits + 1)) //正好或多一个(多一个的原因大家
//可以想一想)
prev->s.next = p->s.next;
else { //偏大,切出需要的一块
p->s.size -= nunits;
p += p->s.size; //被分配块的起始地址
p->s.size = nunits; //填写被分配块大小
}
free_list = prev; //记录前一空块的地址
return(void *)(p+1); //跳过管理块首,返回
}
if(p == free_list)
if((p = Moresys(nunits)) == NULL) //无合适块,向系统申请
return NULL;
}
}

//向系统申请内存空间
static Header* Moresys(unsigned int nu)
{
char *cp;
Header *up;

if(nu<NALLOC)
nu = NALLOC; //向系统申请的最小量
cp = sbrk(nu * sizeof(Header));

printf("sbrk: %X -- %X\n", cp, cp + nu * sizeof(Header)); //调试用
if(cp == (char *) -1)
return NULL; //无空闲页面,返回空地址
up = (Header *)cp; //强制转换成header结构
up->s.size = nu;
Free(up + 1); //将申请到的空闲块链如用户空闲链,指向第二
//个header指针(free函数的要求)
return free_list; //返回free_list指针
}

//回收内存到空闲链上
void Free(void *ap)
{
Header *bp, *p;
bp = (Header *)ap - 1; //指向块首

for(p = free_list; !(bp>p && bp<p->s.next); p = p->s.next) //按地址定位空闲块在链表
//中的位置
if(p>=p->s.next && (bp>p || bp<p->s.next))
break; //空闲块在两端
if(bp + bp->s.size == p->s.next) { //看空闲块是否与已有的块相邻,相邻就合并
bp->s.size += p->s.next->s.size;
bp->s.next = p->s.next->s.next;
}
else
bp->s.next = p->s.next;

if(p + p->s.size == bp) {
p->s.size += bp->s.size;
p->s.next = bp->s.next;
}
else 
p->s.next = bp;

free_list = p;
}

//打印内存分配结果函数
void print_list(void)
{
Header *p;
int i = 0;
printf("base: %X, base.next: %X, base.next.next: %X, free: %X\n", 
&base, base.s.next, base.s.next->s.next, free_list);
for (p = base.s.next; p != &base; p = p->s.next) {
i++;
printf("block %d, size=%d", i, p->s.size);
if(p > free_list)
printf(" It is not searched after this point. \n");
else
printf(" It is a searched free block!\n");
}
}

//测试编写的malloc函数
main()
{
char *p[200];
int i;

for(i = 0; i < 20; i++ ) {
p[i] = (char *)Malloc(8);
printf("malloc %d, %X\n", i , p[i]);
print_list();
}

for (i =0; i < 20; i++) {
Free(p[i]);
printf("free %d\n", i);
print_list();
}
return;
}


抱歉!评论已关闭.