Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1427934
  • 博文数量: 842
  • 博客积分: 12411
  • 博客等级: 上将
  • 技术积分: 5772
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-14 14:43
文章分类

全部博文(842)

文章存档

2013年(157)

2012年(685)

分类: C/C++

2012-05-12 21:48:30

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

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. 主分配程序

点击(此处)折叠或打开

  1. void *malloc(long numbytes) {
  2.     /* Holds where we are looking in memory */
  3.     void *current_location;
  4.     /* This is the same as current_location, but cast to a
  5.      * memory_control_block
  6.     */
  7.     struct mem_control_block *current_location_mcb;
  8.     /* This is the memory location we will return. It will
  9.      * be set to 0 until we find something suitable
  10.     */
  11.     void *memory_location;
  12.     /* Initialize if we haven''t already done so */
  13.     if(! has_initialized) {
  14.          malloc_init();
  15.      }
  16.     /* The memory we search for has to include the memory
  17.      * control block, but the users of malloc don''t need
  18.      * to know this, so we''ll just add it in for them.
  19.     */
  20.      numbytes = numbytes + sizeof(struct mem_control_block);
  21.     /* Set memory_location to 0 until we find a suitable
  22.      * location
  23.     */
  24.      memory_location = 0;
  25.     /* Begin searching at the start of managed memory */
  26.      current_location = managed_memory_start;
  27.     /* Keep going until we have searched all allocated space */
  28.     while(current_location != last_valid_address)
  29.      {
  30.     /* current_location and current_location_mcb point
  31.      * to the same address. However, current_location_mcb
  32.      * is of the correct type, so we can use it as a struct.
  33.      * current_location is a void pointer so we can use it
  34.      * to calculate addresses.
  35.         */
  36.          current_location_mcb =
  37.              (struct mem_control_block *)current_location;
  38.         if(current_location_mcb->is_available)
  39.          {
  40.             if(current_location_mcb->size >= numbytes)
  41.              {
  42.             /* We''ve found an open,
  43.              * appropriately-size location.
  44.                 */
  45.                 /* It is no longer available */
  46.                  current_location_mcb->is_available = 0;
  47.                 /* We own it */
  48.                  memory_location = current_location;
  49.                 /* Leave the loop */
  50.                 break;
  51.              }
  52.          }
  53.         /* If we made it here, it''s because the Current memory
  54.          * block not suitable; move to the next one
  55.         */
  56.          current_location = current_location +
  57.              current_location_mcb->size;
  58.      }
  59.     /* If we still don''t have a valid location, we''ll
  60.      * have to ask the operating system for more memory
  61.     */
  62.     if(! memory_location)
  63.      {
  64.         /* Move the program break numbytes further */
  65.          sbrk(numbytes);
  66.         /* The new memory will be where the last valid
  67.          * address left off
  68.         */
  69.          memory_location = last_valid_address;
  70.         /* We''ll move the last valid address forward
  71.          * numbytes
  72.         */
  73.          last_valid_address = last_valid_address + numbytes;
  74.         /* We need to initialize the mem_control_block */
  75.          current_location_mcb = memory_location;
  76.          current_location_mcb->is_available = 0;
  77.          current_location_mcb->size = numbytes;
  78.      }
  79.     /* Now, no matter what (well, except for error conditions),
  80.      * memory_location has the address of the memory, including
  81.      * the mem_control_block
  82.     */
  83.     /* Move the pointer past the mem_control_block */
  84.      memory_location = memory_location + sizeof(struct mem_control_block);
  85.     /* Return the pointer */
  86.     return memory_location;
  87. }


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

阅读(404) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~