4 * Ullrich von Bassewitz, 03.06.1998
14 void* malloc (size_t size)
15 /* Allocate memory from the given heap. The function returns a pointer to the
16 * allocated memory block or a NULL pointer if not enough memory is available.
17 * Allocating a zero size block is not allowed.
24 /* Check for a size of zero, then add the administration space and round
25 * up the size if needed.
30 size += HEAP_ADMIN_SPACE;
31 if (size < sizeof (struct freeblock)) {
32 size = sizeof (struct freeblock);
35 /* Search the freelist for a block that is big enough */
37 while (f && f->size < size) {
41 /* Did we find one? */
44 /* We found a block big enough. If the block can hold just the
45 * requested size, use the block in full. Beware: When slicing blocks,
46 * there must be space enough to create a new one! If this is not the
47 * case, then use the complete block.
49 if (f->size - size < sizeof (struct freeblock)) {
51 /* Use the actual size */
54 /* Remove the block from the free list */
56 /* We have a previous block */
57 f->prev->next = f->next;
59 /* This is the first block, correct the freelist pointer */
63 /* We have a next block */
64 f->next->prev = f->prev;
66 /* This is the last block, correct the freelist pointer */
72 /* We must slice the block found. Cut off space from the upper
73 * end, so we can leave the actual free block chain intact.
76 /* Decrement the size of the block */
79 /* Set f to the now unused space above the current block */
80 f = (struct freeblock*) (((unsigned) f) + f->size);
84 /* Setup the pointer for the block */
89 /* We did not find a block big enough. Try to use new space from the
92 if (((unsigned) _hend) - ((unsigned) _hptr) < size) {
93 /* Out of heap space */
98 /* There is enough space left, take it from the heap top */
100 _hptr = (unsigned*) (((unsigned) _hptr) + size);
104 /* New block is now in p. Fill in the size and return the user pointer */