www.pudn.com > iccavr_lib.rar > ALLOC.C, change:2002-10-27,size:2682b


#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <_alloc.h> 
 
/* 
#define DEBUG 
*/ 
 
#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); 
	memset(p, 0, size); 
 
	return p; 
	} 
 
void *malloc(size_t size) 
	{ 
	CELL_HDR **qb; 
	CELL_HDR *p, *q; 
	char *cp, *rp; 
	int i; 
 
	size = (size + _BND) & ~_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); 
	/* 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 
		fprintf(stderr, "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) 
		fprintf(stderr, "start %x end %x %s\n", p, p->EndAddr, 
				(p->InUse) ? "!in use!" : ""); 
	} 
#endif