Пример #1
0
void *tmalloc(unsigned nbytes)
{
  CHUNK *p;
  unsigned size;

  if (bot == NULL)
    init();

  size = sizeof(CHUNK) * ((nbytes+sizeof(CHUNK)-1)/sizeof(CHUNK) + 1);

  for (p = bot; p != NULL; p = RIGHT(p))
    if (GET_FREEBIT(p) && CHUNKSIZE(p) >= size)
      break;
  if (p == NULL)
    return NULL;
  
  if (CHUNKSIZE(p) > size)      /* create a remainder chunk */
    {
      CHUNK *q, *pr;

      CLR_FREEBIT(p);           /* required for pointer manipulation */
      q = (CHUNK *)((char *)p + CHUNKSIZE(p) - size);
      pr = p->s.r;
      q->s.l = p; q->s.r = pr;
      p->s.r = q; pr->s.l = q;
      SET_FREEBIT(p);

      p = q;                    /* return q, not the remainder */
    }

  CLR_FREEBIT(p);   //what's going on here?
  return FROMCHUNK(p);
}
Пример #2
0
void tfree(void *vp)
{
  CHUNK *p, *q;

  if (vp == NULL)
    return;

  p = TOCHUNK(vp);
  CLR_FREEBIT(p);
  q = p->s.l;
  if (q != NULL && GET_FREEBIT(q)) /* try to consolidate leftward */
    {
      CLR_FREEBIT(q);
      q->s.r      = p->s.r;
      p->s.r->s.l = q;
      SET_FREEBIT(q);
      p = q;
    }
  q = RIGHT(p);
  if (q != NULL && GET_FREEBIT(q)) /* try to consolidate rightward */
    {
      CLR_FREEBIT(q);
      p->s.r      = q->s.r;
      q->s.r->s.l = p;
      SET_FREEBIT(q);
    }
  SET_FREEBIT(p);
}
Пример #3
0
static void init(void)
{
  bot = &arena[0]; top = &arena[ARENA_CHUNKS-1];
  bot->s.l = NULL; bot->s.r = top;
  top->s.l = bot;  top->s.r = NULL;
  SET_FREEBIT(bot); CLR_FREEBIT(top);
}
Пример #4
0
void *tmalloc(unsigned nbytes)
{
  CHUNK *p;
  unsigned size;

  if (bot == NULL)
    init();

  size = sizeof(CHUNK) * ((nbytes+sizeof(CHUNK)-1)/sizeof(CHUNK) + 1);

  for (p = bot; p != NULL; p = RIGHT(p))
    if (GET_FREEBIT(p) && CHUNKSIZE(p) >= size)
      break;
  if (p == NULL)
    return NULL;

  CLR_FREEBIT(p);
  if (CHUNKSIZE(p) > size)      /* create a remainder chunk */
    {
      CHUNK *q, *pr;
      q = (CHUNK *)(size + (char *)p);
      pr = p->s.r;
      q->s.l = p; q->s.r = pr;
      p->s.r = q; pr->s.l = q;
      SET_FREEBIT(q);
    }
  return FROMCHUNK(p);
}
Пример #5
0
static void init(void)
{
  arena = mmap(HEAP_START, ARENA_CHUNKS * sizeof(CHUNK),
               PROT_READ|PROT_WRITE|PROT_EXEC,
               MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  assert (arena != MAP_FAILED);
  bot = &arena[0]; top = &arena[ARENA_CHUNKS-1];
  bot->s.l = NULL; bot->s.r = top;
  top->s.l = bot;  top->s.r = NULL;
  SET_FREEBIT(bot); CLR_FREEBIT(top);
}