1 /******************************************************************************
2 * Copyright (c) 2004, 2008 IBM Corporation
4 * This program and the accompanying materials
5 * are made available under the terms of the BSD License
6 * which accompanies this distribution, and is available at
7 * http://www.opensource.org/licenses/bsd-license.php
10 * IBM Corporation - initial implementation
11 *****************************************************************************/
17 #include "malloc_defs.h"
20 static int clean(void);
23 /* act points to the end of the initialized heap and the start of uninitialized heap */
26 /* Pointers to start and end of heap: */
27 static char *heap_start, *heap_end;
31 * Standard malloc function
38 size_t blksize; /* size of memory block including the chunk */
40 blksize = size + sizeof(struct chunk);
42 /* has malloc been called for the first time? */
45 /* add some space so we have a good initial playground */
46 initsize = (blksize + 0x1000) & ~0x0fff;
47 /* get initial memory region with sbrk() */
48 heap_start = sbrk(initsize);
49 if (heap_start == (void*)-1)
51 heap_end = heap_start + initsize;
56 data = act + sizeof(struct chunk);
58 /* Check if there is space left in the uninitialized part of the heap */
59 if (act + blksize > heap_end) {
60 //search at begin of heap
63 while ((((struct chunk *) header)->inuse != 0
64 || ((struct chunk *) header)->length < size)
66 header = header + sizeof(struct chunk)
67 + ((struct chunk *) header)->length;
70 // check if heap is full
73 // merging of free blocks succeeded, so try again
75 } else if (sbrk(blksize) == heap_end) {
76 // succeeded to get more memory, so try again
80 // No more memory available
85 // Check if we need to split this memory block into two
86 if (((struct chunk *) header)->length > blksize) {
87 //available memory is too big
90 alt = ((struct chunk *) header)->length;
91 ((struct chunk *) header)->inuse = 1;
92 ((struct chunk *) header)->length = size;
93 data = header + sizeof(struct chunk);
95 //mark the rest of the heap
97 ((struct chunk *) header)->inuse = 0;
98 ((struct chunk *) header)->length =
101 //new memory matched exactly in available memory
102 ((struct chunk *) header)->inuse = 1;
103 data = header + sizeof(struct chunk);
108 ((struct chunk *) header)->inuse = 1;
109 ((struct chunk *) header)->length = size;
119 * Merge free memory blocks in initialized heap if possible
129 //if (act == 0) // This should never happen
132 while (header < act) {
134 if (((struct chunk *) header)->inuse == 0) {
135 if (firstfree == 0) {
136 /* First free block in a row, only save address */
140 /* more than one free block in a row, merge them! */
141 ((struct chunk *) firstfree)->length +=
142 ((struct chunk *) header)->length +
143 sizeof(struct chunk);
151 header = header + sizeof(struct chunk)
152 + ((struct chunk *) header)->length;