1 /* ----------------------------------------------------------------------------
3 * ----------------------------------------------------------------------------
4 * Public Domain C Library - http://pdclib.sourceforge.net
5 * This code is Public Domain. Use, modify, and redistribute at will.
6 * --------------------------------------------------------------------------*/
10 void * malloc( size_t size ) { /* TODO */ };
12 /* This is a simple best-fit / first-fit implementation heavily based on
13 * Thomas "Beyond Infinity" Kreitner's code
16 /* memory list element */
30 size_t heap_start = 0xa0000000;
31 size_t heap_used = 0x00000050; /* HEAP in use. Holds the next FREE address (?) */
32 size_t heap_max = 0xfffffff; /* max. HEAP */
34 static struct memlist_t free_mem = { (struct memlist_t *) heap_start,
35 (struct memlist_t *) heap_start };
36 /* free_mem.start->next = NULL; */
38 static struct memlist_t used_mem = { (struct memlist_t *) heap_start + sizeof( chunk_t ),
39 (struct memlist_t *) heap_start + sizeof( chunk_t ) };
40 /* used_mem.start->next = NULL; */
42 void * malloc( size_t size )
46 if ( free_mem.start != free_mem.last )
48 /* first pass: exact fit */
49 chunk = free_mem.start;
54 if ( ( chunk == NULL ) || ( chunk->size == size ) )
62 /* second pass - first fit */
63 chunk = free_mem.start;
68 if ( ( chunk == NULL ) || ( chunk->size > size ) )
76 /* remove chunk from free_mem list */
77 if ( free_mem.start->next->next == NULL )
79 /* free_mem list has only one entry */
80 free_mem.last = free_mem.start;
82 else if ( chunk == free_mem.last )
84 /* chunk is last element of free_mem list */
85 prev_chunk->next = NULL;
86 free_mem.last = prev_chunk;
90 /* chunk is neither only nor last in free_mem list */
91 prev_chunk->next = prev_chunk->next->next;
93 /* append chunk to used_mem list */
95 used_mem.last->next = chunk;
96 used_mem.last = chunk;
98 /* append new chunk to end of used_mem list (if there's space) */
101 if ( ( heap_used + size ) <= heap_max )
103 /* building the header */
104 chunk = (chunk_t *) heap_start + heap_used + 1;
107 chunk->address = chunk + sizeof( chunk_t );
108 /* push heap_used past allocated area */
109 heap_used += sizeof( chunk_t ) + size;
110 used_mem.last->next = chunk;
111 used_mem.last = chunk;
115 /* allocation would exceed max. heap size -
116 /* demand more memory from kernel - not implemented */
120 return (void *) chunk->address;