2 * malloc.c - dynamic memory allocation
4 * written by Vangelis Rokas, 2004 (vrokas@otenet.gr)
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2, or (at your option) any
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * In other words, you are welcome to use, share and improve this program.
21 * You are forbidden to forbid anyone else to use, share and improve
22 * what you give them. Help stamp out software-hoarding!
24 * $Id: malloc.c 3835 2005-08-07 20:09:11Z tecodev $
29 /* this is an external pointer to HEAP. It should be defined in
30 * the user's program, or it can be a symbol created by linker */
31 extern unsigned char _MALLOC_SPEC *heap;
33 unsigned char _MALLOC_SPEC *malloc(unsigned char len)
35 _malloc_rec _MALLOC_SPEC *pHeap; /* pointer to block header */
36 _malloc_rec _MALLOC_SPEC *temp;
37 unsigned char bLen, eLen; /* size of block */
42 if(len >= MAX_BLOCK_SIZE)
45 pHeap = (_malloc_rec _MALLOC_SPEC *)&heap;
48 bLen = pHeap->bits.count;
50 /* if datum is zero, then last block, return NULL */
51 if(pHeap->datum == 0) {
58 /* in the first pass, we search for blocks that have
59 * the requested size, in the second pass, try to merge
60 * adjacent blocks to 'make' the requested block */
61 pHeap = (_malloc_rec _MALLOC_SPEC *)&heap;
67 /* if current block is allocated then proceed to next */
72 /* current block is not allocated, try to allocate */
74 /* if current block is not enough for allocation, then proceed to next */
78 /* if we are in the first pass, check next block */
82 /* otherwise try merge */
85 temp = _mergeHeapBlock(pHeap, len);
88 /* otherwise proceed with next block */
91 //pHeap = temp; /* temp == pHeap */
92 bLen = pHeap->bits.count;
95 /* current block is enough to hold the new block */
97 /* allocate by filling the fields */
99 pHeap->datum = 0x80 | eLen;
102 /* if current block size is greater than the requested one,
103 * create a new empty block at the end of the newly allocated */
104 temp = (_malloc_rec _MALLOC_SPEC *)((unsigned int)pHeap + eLen);
105 temp->datum = (bLen - eLen);
108 return ((unsigned char _MALLOC_SPEC *)((unsigned int)pHeap + 1));
111 pHeap = (_malloc_rec _MALLOC_SPEC *)((unsigned int)pHeap + bLen);
115 return ((unsigned char _MALLOC_SPEC *)0);