VC++中malloc函数源代码

作者在 2008-04-10 18:20:18 发布以下内容

VC++中malloc函数源代码
/***
*malloc.c - Get a block of memory from the heap
*
*       Copyright (c) 1989-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
*       Defines the malloc() function.
*
*******************************************************************************/

#include <cruntime.h>
#include <malloc.h>
#include <internal.h>
#include <mtdll.h>
#include <dbgint.h>

#ifdef WINHEAP
#include <windows.h>
#include <winheap.h>
#else  /* WINHEAP */
#include <heap.h>
#endif  /* WINHEAP */


extern int _newmode;    /* malloc new() handler mode */


/***
*void *malloc(size_t size) - Get a block of memory from the heap
*
*Purpose:
*       Allocate of block of memory of at least size bytes from the heap and
*       return a pointer to it.
*
*       Calls the new appropriate new handler (if installed).
*
*Entry:
*       size_t size - size of block requested
*
*Exit:
*       Success:  Pointer to memory block
*       Failure:  NULL (or some error value)
*
*Uses:
*
*Exceptions:
*
*******************************************************************************/

void * __cdecl _malloc_base (size_t size)

{
        return _nh_malloc_base(size, _newmode);
}


/***
*void *_nh_malloc_base(size_t size) - Get a block of memory from the heap
*
*Purpose:
*       Allocate of block of memory of at least size bytes from the heap and
*       return a pointer to it.
*
*       Calls the appropriate new handler (if installed).
*
*       There are two distinct new handler schemes supported. The 'new' ANSI
*       C++ scheme overrides the 'old' scheme when it is activated. A value of
*       _NOPTH for the 'new' handler indicates that it is inactivated and the
*       'old' handler is then called.
*
*Entry:
*       size_t size - size of block requested
*
*Exit:
*       Success:  Pointer to memory block
*       Failure:  NULL (or some error value)
*
*Uses:
*
*Exceptions:
*
*******************************************************************************/

void * __cdecl _nh_malloc_base (size_t size, int nhFlag)
{
        void * pvReturn;

        //  validate size
        if (size > _HEAP_MAXREQ)
            return NULL;

#ifndef WINHEAP
        /* round requested size */
        size = _ROUND2(size, _GRANULARITY);
#endif  /* WINHEAP */

        for (;;) {

            //  allocate memory block
            if (size <= _HEAP_MAXREQ)
                pvReturn = _heap_alloc_base(size);
            else
                pvReturn = NULL;

            //  if successful allocation, return pointer to memory
            //  if new handling turned off altogether, return NULL

            if (pvReturn || nhFlag == 0)
                return pvReturn;

            //  call installed new handler
            if (!_callnewh(size))
                return NULL;

            //  new handler was successful -- try to allocate again
        }
}

/***
*void *_heap_alloc_base(size_t size) - does actual allocation
*
*Purpose:
*       Same as malloc() except the new handler is not called.
*
*Entry:
*       See malloc
*
*Exit:
*       See malloc
*
*Exceptions:
*
*******************************************************************************/

void * __cdecl _heap_alloc_base (size_t size)

{
#ifdef WINHEAP
        void * pvReturn;
#else  /* WINHEAP */
        _PBLKDESC pdesc;
        _PBLKDESC pdesc2;
#endif  /* WINHEAP */


#ifdef WINHEAP

        if (size <= __sbh_threshold)
        {
            _mlock(_HEAP_LOCK);
            pvReturn = __sbh_alloc_block(size);
            _munlock(_HEAP_LOCK);
            if (pvReturn)
                return pvReturn;
        }

        if (size == 0)
            size = 1;
        size = (size + BYTES_PER_PARA - 1) & ~(BYTES_PER_PARA - 1);
        return HeapAlloc(_crtheap, 0, size);
}

#else  /* WINHEAP */

        /* try to find a big enough free block
         */
        if ( (pdesc = _heap_search(size)) == NULL )
        {
            if ( _heap_grow(size) != -1 )
            {
                /* try finding a big enough free block again. the
                 * success of the call to _heap_grow should guarantee
                 * it, but...
                 */
                if ( (pdesc = _heap_search(size)) == NULL )
                {
                    /* something unexpected, and very bad, has
                     * happened. abort!
                     */
                    _heap_abort();
                }
            }
            else
                return NULL;
        }

        /* carve the block into two pieces (if necessary). the first piece
         * shall be of the exact requested size, marked inuse and returned to
         * the caller. the leftover piece is to be marked free.
         */
        if ( _BLKSIZE(pdesc) != size ) {
            /* split up the block and free the leftover piece back to
             * the heap
             */
            if ( (pdesc2 = _heap_split_block(pdesc, size)) != NULL )
                _SET_FREE(pdesc2);
        }

        /* mark pdesc inuse
         */
        _SET_INUSE(pdesc);

        /* check proverdesc and reset, if necessary
         */

        _heap_desc.proverdesc = pdesc->pnextdesc;

        return( (void *)((char *)_ADDRESS(pdesc) + _HDRSIZE) );
}


/***
*_PBLKDESC _heap_split_block(pdesc, newsize) - split a heap allocation block
*       into two allocation blocks
*
*Purpose:
*       Split the allocation block described by pdesc into two blocks, the
*       first one being of newsize bytes.
*
*       Notes: It is caller's responsibilty to set the status (i.e., free
*       or inuse) of the two new blocks, and to check and reset proverdesc
*       if necessary. See Exceptions (below) for additional requirements.
*
*Entry:
*       _PBLKDESC pdesc - pointer to the allocation block descriptor
*       size_t newsize  - size for the first of the two sub-blocks (i.e.,
*                 (i.e., newsize == _BLKSIZE(pdesc), on exit)
*
*Exit:
*       If successful, return a pointer to the descriptor for the leftover
*       block.
*       Otherwise, return NULL.
*
*Exceptions:
*       It is assumed pdesc points to a valid allocation block descriptor and
*       newsize is a valid heap block size as is (i.e., WITHOUT rounding). If
*       either of these of assumption is violated, _heap_split_block() will
*       likely corrupt the heap. Note also that _heap_split_block will simply
*       return to the caller if newsize >= _BLKSIZE(pdesc), on entry.
*
*******************************************************************************/

_PBLKDESC __cdecl _heap_split_block (
        REG1 _PBLKDESC pdesc,
        size_t newsize
        )
{
        REG2 _PBLKDESC pdesc2;

        _ASSERTE(("_heap_split_block: bad pdesc arg", _CHECK_PDESC(pdesc)));
        _ASSERTE(("_heap_split_block: bad newsize arg", _ROUND2(newsize,_GRANULARITY) == newsize));

        /* carve the block into two pieces (if possible). the first piece
         * is to be exactly newsize bytes.
         */
        if ( (_BLKSIZE(pdesc) > newsize) && ((pdesc2 = __getempty())
               != NULL) )
        {
            /* set it up to manage the second piece and link it in to
             * the list
             */
            pdesc2->pblock = (void *)((char *)_ADDRESS(pdesc) + newsize +
                     _HDRSIZE);
            *(void **)(pdesc2->pblock) = pdesc2;
            pdesc2->pnextdesc = pdesc->pnextdesc;
            pdesc->pnextdesc = pdesc2;

            return pdesc2;
        }
        return NULL;
}

#endif  /* WINHEAP */


 

文件: MALLOC.rar
技术 | 阅读 7448 次
文章评论,共1条
vfdff(作者)
2009-07-05 11:06
1
浅析malloc()的几种实现方式<br />
来源:嵌入式在线 作者:上海交通大学计算机科学与工程系 孙高鑫 时间:2007-06-22 发布人:卢春妙<br />
  malloc()是C语言中动态存储管理的一组标准库函数之一。其作用是在内存的动态存储区中分配一个长度为size的连续空间。其参数是一个无符号整形数,返回值是一个指向所分配的连续存储域的起始地址的指针。<br />
<br />
  动态内存分配就是指在程序执行的过程中动态地分配或者回收存储空间的分配内存的方法。动态内存分配不像数组等静态内存分配方法那样需要预先分配存储空间,而是由系统根据程序的需要即时分配,且分配的大小就是程序要求的大小。本文简单介绍动态内存分配函数malloc()及几种实现方法。<br />
<br />
1. 简介<br />
<br />
  malloc()是C语言中动态存储管理的一组标准库函数之一。其作用是在内存的动态存储区中分配一个长度为size的连续空间。其参数是一个无符号整形数,返回值是一个指向所分配的连续存储域的起始地址的指针。还有一点必须注意的是,当函数未能成功分配存储空间(如内存不足)就会返回一个NULL指针。所以在调用该函数时应该检测返回值是否为NULL并执行相应的操作。<br />
<br />
2. 函数说明<br />
<br />
  C语言的动态存储管理由一组标准库函数实现,其原型在标准文件&lt;stdlib.h&gt;里描述,需要用这些功能时应包含这个文件。与动态存储分配有关的函数共有四个,其中就包括存储分配函数malloc()。函数原型是:void *malloc (size_t n);这里的size_t是标准库里定义的一个类型,它是一个无符号整型。这个整型能够满足所有对存储块大小描述的需要,具体相当于哪个整型由具体的C系统确定。malloc的返回值为(void *)类型(这是通用指针的一个重要用途),它分配一片能存放大小为n的数据的存储块,返回对应的指针值;如果不能满足申请(找不到能满足要求的存储块)就返回NULL。在使用时,应该把malloc的返回值转换到特定指针类型,赋给一个指针。<br />
<br />
  注意,虽然这里的存储块是通过动态分配得到的,但是它的大小也是确定的,同样不允许越界使用。例如上面程序段分配的块里能存n个双精度数据,随后的使用就必须在这个范围内进行。越界使用动态分配的存储块,尤其是越界赋值,可能引起非常严重的后果,通常会破坏程序的运行系统,可能造成本程序或者整个计算机系统垮台。<br />
<br />
  下例是一个动态分配的例子:<br />
#include &lt;stdlib.h&gt;<br />
<br />
main()<br />
{<br />
 int count,*array; /*count是一个计数器,array是一个整型指针,也可以理解为指向一个整型数组的首地址*/<br />
 if((array(int *) malloc (10*sizeof(int)))==NULL)<br />
 {<br />
  printf(&quot;不能成功分配存储空间。&quot;);<br />
  exit(1);<br />
 }<br />
 for (count=0;count〈10;count++) /*给数组赋值*/<br />
  array[count]=count;<br />
 for(count=0;count〈10;count++) /*打印数组元素*/<br />
  printf(&quot;%2d&quot;,array[count]);<br />
}<br />
<br />
  上例中动态分配了10个整型存储区域,然后进行赋值并打印。例中if((array(int *) malloc (10*sizeof(int)))==NULL)语句可以分为以下几步:<br />
  1)分配10个整型的连续存储空间,并返回一个指向其起始地址的整型指针<br />
  2)把此整型指针地址赋给array<br />
  3)检测返回值是否为NULL<br />
<br />
3. malloc()工作机制<br />
<br />
  malloc函数的实质体现在,它有一个将可用的内存块连接为一个长长的列表的所谓空闲链表。调用malloc函数时,它沿连接表寻找一个大到足以满足用户请求所需要的内存块。然后,将该内存块一分为二(一块的大小与用户请求的大小相等,另一块的大小就是剩下的字节)。接下来,将分配给用户的那块内存传给用户,并将剩下的那块(如果有的话)返回到连接表上。调用free函数时,它将用户释放的内存块连接到空闲链上。到最后,空闲链会被切成很多的小内存片段,如果这时用户申请一个大的内存片段,那么空闲链上可能没有可以满足用户要求的片段了。于是,malloc函数请求延时,并开始在空闲链上翻箱倒柜地检查各内存片段,对它们进行整理,将相邻的小空闲块合并成较大的内存块。<br />
<br />
4. malloc()在操作系统中的实现<br />
<br />
  在 C 程序中,多次使用malloc () 和 free()。不过,您可能没有用一些时间去思考它们在您的操作系统中是如何实现的。本节将向您展示 malloc 和 free 的一个最简化实现的代码,来帮助说明管理内存时都涉及到了哪些事情。<br />
<br />
  在大部分操作系统中,内存分配由以下两个简单的函数来处理:<br />
<br />
  void *malloc (long numbytes):该函数负责分配 numbytes 大小的内存,并返回指向第一个字节的指针。<br />
<br />
  void free(void *firstbyte):如果给定一个由先前的 malloc 返回的指针,那么该函数会将分配的空间归还给进程的“空闲空间”。<br />
<br />
  malloc_init 将是初始化内存分配程序的函数。它要完成以下三件事:将分配程序标识为已经初始化,找到系统中最后一个有效内存地址,然后建立起指向我们管理的内存的指针。这三个变量都是全局变量:<br />
<br />
  清单 1. 我们的简单分配程序的全局变量<br />
<br />
int has_initialized = 0;<br />
void *managed_memory_start;<br />
void *last_valid_address;<br />
<br />
  如前所述,被映射的内存的边界(最后一个有效地址)常被称为系统中断点或者 当前中断点。在很多 UNIX? 系统中,为了指出当前系统中断点,必须使用 sbrk(0) 函数。 sbrk 根据参数中给出的字节数移动当前系统中断点,然后返回新的系统中断点。使用参数 0 只是返回当前中断点。这里是我们的 malloc 初始化代码,它将找到当前中断点并初始化我们的变量:<br />
<br />
  清单 2. 分配程序初始化函数<br />
/* Include the sbrk function */<br />
<br />
#include<br />
void malloc_init()<br />
{<br />
/* grab the last valid address from the OS */<br />
last_valid_address = sbrk(0);<br />
/* we don't have any memory to manage yet, so<br />
*just set the beginning to be last_valid_address<br />
*/<br />
managed_memory_start = last_valid_address;<br />
/* Okay, we're initialized and ready to go */<br />
has_initialized = 1;<br />
}<br />
<br />
  现在,为了完全地管理内存,我们需要能够追踪要分配和回收哪些内存。在对内存块进行了 free 调用之后,我们需要做的是诸如将它们标记为未被使用的等事情,并且,在调用 malloc 时,我们要能够定位未被使用的内存块。因此, malloc 返回的每块内存的起始处首先要有这个结构:<br />
<br />
  清单 3. 内存控制块结构定义<br />
struct mem_control_block {<br />
int is_available;<br />
int size;<br />
};<br />
<br />
   现在,您可能会认为当程序调用 malloc 时这会引发问题 —— 它们如何知道这个结构?答案是它们不必知道;在返回指针之前,我们会将其移动到这个结构之后,把它隐藏起来。这使得返回的指针指向没有用于任何其他用途的内存。那样,从调用程序的角度来看,它们所得到的全部是空闲的、开放的内存。然后,当通过 free() 将该指针传递回来时,我们只需要倒退几个内存字节就可以再次找到这个结构。<br />
<br />
  在讨论分配内存之前,我们将先讨论释放,因为它更简单。为了释放内存,我们必须要做的惟一一件事情就是,获得我们给出的指针,回退 sizeof(struct mem_control_block) 个字节,并将其标记为可用的。这里是对应的代码:<br />
<br />
  清单 4. 解除分配函数<br />
void free(void *firstbyte) {<br />
struct mem_control_block *mcb;<br />
/* Backup from the given pointer to find the<br />
* mem_control_block<br />
*/<br />
mcb = firstbyte - sizeof(struct mem_control_block);<br />
/* Mark the block as being available */<br />
mcb-&gt;is_available = 1;<br />
/* That's It! We're done. */<br />
return;<br />
}<br />
<br />
  如您所见,在这个分配程序中,内存的释放使用了一个非常简单的机制,在固定时间内完成内存释放。分配内存稍微困难一些。以下是该算法的略述:<br />
<br />
  清单 5. 主分配程序的伪代码<br />
1. If our allocator has not been initialized, initialize it.<br />
2. Add sizeof(struct mem_control_block) to the size requested.<br />
3. start at managed_memory_start.<br />
4. Are we at last_valid address?<br />
5. If we are:<br />
A. We didn't find any existing space that was large enough<br />
-- ask the operating system for more and return that.<br />
6. Otherwise:<br />
A. Is the current space available (check is_available from<br />
the mem_control_block)?<br />
B. If it is:<br />
i) Is it large enough (check &quot;size&quot; from the<br />
mem_control_block)?<br />
ii) If so:<br />
a. Mark it as unavailable<br />
b. Move past mem_control_block and return the<br />
pointer<br />
iii) Otherwise:<br />
a. Move forward &quot;size&quot; bytes<br />
b. Go back go step 4<br />
C. Otherwise:<br />
i) Move forward &quot;size&quot; bytes<br />
ii) Go back to step 4<br />
<br />
  我们主要使用连接的指针遍历内存来寻找开放的内存块。这里是代码:<br />
<br />
  清单 6. 主分配程序<br />
void *malloc(long numbytes) {<br />
/* Holds where we are looking in memory */<br />
void *current_location;<br />
/* This is the same as current_location, but cast to a<br />
* memory_control_block<br />
*/<br />
struct mem_control_block *current_location_mcb;<br />
/* This is the memory location we will return. It will<br />
* be set to 0 until we find something suitable<br />
*/<br />
void *memory_location;<br />
/* Initialize if we haven't already done so */<br />
if(! has_initialized) {<br />
malloc_init();<br />
}<br />
/* The memory we search for has to include the memory<br />
* control block, but the users of malloc don't need<br />
* to know this, so we'll just add it in for them.<br />
*/<br />
numbytes = numbytes + sizeof(struct mem_control_block);<br />
/* Set memory_location to 0 until we find a suitable<br />
* location<br />
*/<br />
memory_location = 0;<br />
/* Begin searching at the start of managed memory */<br />
current_location = managed_memory_start;<br />
/* Keep going until we have searched all allocated space */<br />
while(current_location != last_valid_address)<br />
{<br />
/* current_location and current_location_mcb point<br />
* to the same address. However, current_location_mcb<br />
* is of the correct type, so we can use it as a struct.<br />
* current_location is a void pointer so we can use it<br />
* to calculate addresses.<br />
*/<br />
current_location_mcb =<br />
(struct mem_control_block *)current_location;<br />
if(current_location_mcb-&gt;is_available)<br />
{<br />
if(current_location_mcb-&gt;size &gt;= numbytes)<br />
{<br />
/* Woohoo! We've found an open,<br />
* appropriately-size location.<br />
*/<br />
/* It is no longer available */<br />
current_location_mcb-&gt;is_available = 0;<br />
/* We own it */<br />
memory_location = current_location;<br />
/* Leave the loop */<br />
break;<br />
}<br />
}<br />
/* If we made it here, it's because the Current memory<br />
* block not suitable; move to the next one<br />
*/<br />
current_location = current_location +<br />
current_location_mcb-&gt;size;<br />
}<br />
/* If we still don't have a valid location, we'll<br />
* have to ask the operating system for more memory<br />
*/<br />
if(! memory_location)<br />
{<br />
/* Move the program break numbytes further */<br />
sbrk(numbytes);<br />
/* The new memory will be where the last valid<br />
* address left off<br />
*/<br />
memory_location = last_valid_address;<br />
/* We'll move the last valid address forward<br />
* numbytes<br />
*/<br />
last_valid_address = last_valid_address + numbytes;<br />
/* We need to initialize the mem_control_block */<br />
current_location_mcb = memory_location;<br />
current_location_mcb-&gt;is_available = 0;<br />
current_location_mcb-&gt;size = numbytes;<br />
}<br />
/* Now, no matter what (well, except for error conditions),<br />
* memory_location has the address of the memory, including<br />
* the mem_control_block<br />
*/<br />
/* Move the pointer past the mem_control_block */<br />
memory_location = memory_location + sizeof(struct mem_control_block);<br />
/* Return the pointer */<br />
return memory_location;<br />
}<br />
<br />
  这就是我们的内存管理器。现在,我们只需要构建它,并在程序中使用它即可。<br />
<br />
5. malloc()的其他实现<br />
<br />
  malloc() 的实现有很多,这些实现各有优点与缺点。在设计一个分配程序时,要面临许多需要折衷的选择,其中包括:<br />
<br />
  分配的速度。<br />
  回收的速度。<br />
  有线程的环境的行为。<br />
  内存将要被用光时的行为。<br />
  局部缓存。<br />
  簿记(Bookkeeping)内存开销。<br />
  虚拟内存环境中的行为。<br />
  小的或者大的对象。<br />
  实时保证。<br />
  每一个实现都有其自身的优缺点集合。在我们的简单的分配程序中,分配非常慢,而回收非常快。另外,由于它在使用虚拟内存系统方面较差,所以它最适于处理大的对象。<br />
<br />
  还有其他许多分配程序可以使用。其中包括:<br />
<br />
  Doug Lea Malloc:Doug Lea Malloc 实际上是完整的一组分配程序,其中包括 Doug Lea 的原始分配程序,GNU libc 分配程序和 ptmalloc。 Doug Lea 的分配程序有着与我们的版本非常类似的基本结构,但是它加入了索引,这使得搜索速度更快,并且可以将多个没有被使用的块组合为一个大的块。它还支持缓存,以便更快地再次使用最近释放的内存。 ptmalloc 是 Doug Lea Malloc 的一个扩展版本,支持多线程。在本文后面的参考资料部分中,有一篇描述 Doug Lea 的 Malloc 实现的文章。<br />
<br />
  BSD Malloc:BSD Malloc 是随 4.2 BSD 发行的实现,包含在 FreeBSD 之中,这个分配程序可以从预先确实大小的对象构成的池中分配对象。它有一些用于对象大小的 size 类,这些对象的大小为 2 的若干次幂减去某一常数。所以,如果您请求给定大小的一个对象,它就简单地分配一个与之匹配的 size 类。这样就提供了一个快速的实现,但是可能会浪费内存。在 参考资料部分中,有一篇描述该实现的文章。<br />
<br />
  Hoard:编写 Hoard 的目标是使内存分配在多线程环境中进行得非常快。因此,它的构造以锁的使用为中心,从而使所有进程不必等待分配内存。它可以显著地加快那些进行很多分配和回收的多线程进程的速度。在 参考资料部分中,有一篇描述该实现的文章。<br />
众多可用的分配程序中最有名的就是上述这些分配程序。如果您的程序有特别的分配需求,那么您可能更愿意编写一个定制的能匹配您的程序内存分配方式的分配程序。不过,如果不熟悉分配程序的设计,那么定制分配程序通常会带来比它们解决的问题更多的问题。<br />
<br />
6. 结束语<br />
<br />
  前面已经提过,多次调用malloc()后空闲内存被切成很多的小内存片段,这就使得用户在申请内存使用时,由于找不到足够大的内存空间,malloc()需要进行内存整理,使得函数的性能越来越低。聪明的程序员通过总是分配大小为2的幂的内存块,而最大限度地降低潜在的malloc性能丧失。也就是说,所分配的内存块大小为4字节、8字节、16字节、18446744073709551616字节,等等。这样做最大限度地减少了进入空闲链的怪异片段(各种尺寸的小片段都有)的数量。尽管看起来这好像浪费了空间,但也容易看出浪费的空间永远不会超过50%。<br />
<br />
参考文献:<br />
<br />
[1] Jonathan Bartlett,内存管理内幕. developerWorks 中国,2004年11月<br />
[2] Jan Lindblad,内存碎片处理技术. EDN电子设计技术,2004年10月08日
游客请输入验证码
浏览1943833次