📄 alloc.c
字号:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <_alloc.h>
#ifdef DEBUG
#define calloc xcalloc
#define malloc xmalloc
#define realloc xrealloc
#define free xfree
void *malloc(), *realloc(), *calloc();
void free();
#endif
void *calloc(size_t nelem, size_t size)
{
void *p;
size *= nelem;
p = malloc(size);
if (p == 0)
return 0;
memset(p, 0, size);
return p;
}
void *malloc(size_t size)
{
CELL_HDR **qb;
CELL_HDR *p, *q;
char *cp, *rp;
int i;
size = roundup(size, _BND);
for (qb = &__FreeList; p = *qb; qb = &(*qb)->next)
if (size <= p->size)
{
if (DELTA < p->size - size)
{
/* some space left, link it to the free list
*/
q = (CELL_HDR *)INCR_SIZE(p, size);
q->next = p->next;
q->size = p->size - REAL_SIZE(size);
q->size &= ~_BND;
q->EndAddr = p->EndAddr;
#ifdef DEBUG
q->InUse = 0;
#endif
p->EndAddr = q;
p->size = NEW_SIZE(p, p->EndAddr);
*qb = q;
}
else
*qb = p->next;
p->next = 0;
#ifdef DEBUG
p->InUse = 1;
#endif
cp = INCR_SIZE(p, 0);
return cp;
}
return 0;
}
void *realloc(void *p, size_t size)
{
CELL_HDR *cell = GET_HDR(p);
void *q;
if ((char *)cell->EndAddr >= (char *)p + size)
{
cell->size = size;
return p;
}
q = malloc(size);
if (q == 0)
return 0;
/* copy only the beginning portion
*/
if (size > cell->size)
size = cell->size;
memcpy(q, p, size);
free(p);
return q;
}
static void Merge(CELL_HDR *cell)
{
CELL_HDR **qb;
CELL_HDR *p;
for (qb = &__FreeList; p = *qb; qb = &(*qb)->next)
/* merge with next chunk
*/
if (cell->EndAddr == p)
{
*qb = p->next;
cell->size += REAL_SIZE(p->size); /* Added by wph */
cell->EndAddr = p->EndAddr;
Merge(cell);
break;
}
/* merge with previous chunk
*/
else if (p->EndAddr == cell)
{
*qb = p->next;
p->size += REAL_SIZE(cell->size); /* Added by wph */
p->EndAddr = cell->EndAddr;
Merge(p);
break;
}
if (!p)
{
cell->next = __FreeList;
__FreeList = cell;
}
}
void free(void *p)
{
CELL_HDR *cell;
if (!p)
return;
cell = GET_HDR(p);
if ((char *)cell->EndAddr < INCR_SIZE(cell, cell->size)
#ifdef DEBUG
|| !cell->InUse
#endif
)
{
#ifdef DEBUG
printf("bad memory %x\n", p);
#endif
return;
}
#ifdef DEBUG
cell->InUse = 0;
#endif
Merge(cell);
}
#ifdef DEBUG
void _PrintMemList(void)
{
CELL_HDR *p;
for (p = __FreeList; p; p = p->next)
printf("start %x end %x %s\n", p, p->EndAddr,
(p->InUse) ? "!in use!" : "");
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -