2 * malloc.c - dynamic memory allocation
4 * written by Vangelis Rokas, 2004 (vrokas@otenet.gr)
10 extern unsigned char *_dynamicHeap; /* pointer to heap */
12 unsigned char *malloc(unsigned char len)
14 _malloc_rec *pHeap; /* pointer to block header */
16 unsigned char bLen; /* size of block */
19 if(len > _MAX_HEAP_SIZE)
20 return ((unsigned char *)0);
22 pHeap = (_malloc_rec *)&_dynamicHeap;
26 bLen = pHeap->bits.count;
28 /* if datum is zero, then last block, return NULL */
30 return ((unsigned char *)0);
32 /* if current block is allocated then proceed to next */
33 if(pHeap->bits.alloc) {
34 pHeap += pHeap->bits.count;
39 /* current block is not allocated, try to allocate */
41 /* if current block is not enough for allocation, then proceed to next */
44 /* current block is not enough see if we can merge some adjacent
45 * memory blocks to make it fit */
46 temp = pHeap + pHeap->bits.count;
48 while((temp->datum) && (!temp->bits.alloc) && (eLen < len)) {
49 eLen += temp->bits.count;
50 temp += temp->bits.count;
55 /* yes, there are some free blocks that can be merged, merge them... */
59 if(eLen > MAX_BLOCK_SIZE)i = MAX_BLOCK_SIZE;
69 bLen = pHeap->bits.count;
71 /* otherwise proceed with next block */
72 pHeap += pHeap->bits.count;
78 /* current block is enough to hold the new block */
80 /* allocate by filling the fields */
81 pHeap->bits.count = len+1;
82 pHeap->bits.alloc = 1;
85 /* if current block size is greater than the requested one,
86 * create a new empty block at the end of the newly allocated */
88 temp->bits.count = bLen - len - 1;
92 return ((unsigned char *)pHeap + 1);