morecore的代码:
#define NALLOC /*minimun units to request*/
/*morecore ask system for more memory*/
static Header* morecore(unsigned nu)
{
char *cp,*sbrk(int);
Header *up;
if(nu<NALLOC)
{
nu = NALLOC;
}
cp =sbrk(nu *sizeof(Header));
if(cp == (char*)-1) /*no space at all*/
{
return NULL:
}
up = (Header*) cp;
up->s.size = nu;
free(void *)(up+1));
return freep;
}
sbrk(int n)是系统调用,功能是"return a pointer to n more bytes of storage"
我刚看完英文版的《the c programming language》(花了两个月,呵呵),现学现卖。
在该书的第185-189页,有详细的说明,在unix下的实现。
/*内存块的数据结构*/
typedef long Align /*for allignment to long boundary*/
union header /* block header */
{
struct
{
union header *ptr; /* next block if on free list */
unsigned size; /* size of this block */
}
Align x; /* force alignment of blocks*/
};
typedef union header Header;