comparison src/std.c @ 22:3fb0ec050ff3

malloc has been restructured to now work in a more logical manner malloc now allocates memory from the beginning of a block instead of the end. Additionally, memory is now 8-byte aligned instead of 16-byte aligned. malloc_init should now be called to set up all the memory information. Fixed a bug where malloc would not have iterated to find new memory locations.
author Jonathan Pevarnek <pevarnj@gmail.com>
date Wed, 16 Mar 2011 00:09:35 -0400
parents 7c2adb65ceac
children f68b59af5ea6
comparison
equal deleted inserted replaced
21:7c2adb65ceac 22:3fb0ec050ff3
126 return ret; 126 return ret;
127 } 127 }
128 128
129 static Block *allocp = NULL; //the location of the last item allocated by malloc 129 static Block *allocp = NULL; //the location of the last item allocated by malloc
130 130
131 void malloc_init(size_t memSize)
132 {
133 allocp = (void*)0x200000;
134 allocp->next = allocp;
135 allocp->size = memSize/sizeof(u64);
136 }
137
131 void* malloc(size_t size) 138 void* malloc(size_t size)
132 { 139 {
133 unsigned int nBlocks = 1 + (size + sizeof(Block) - 1)/sizeof(Block); 140 unsigned int nUnits = ((size + sizeof(Block)) + sizeof(u64) - 1)/sizeof(u64);
134 //We are allocating a number of blocks equal to the number needed rounded up 141 Block *cur, *prev, *temp;
135 //plus one for the actual info block 142 if(allocp == NULL) return NULL;
136 Block *cur, *prev;
137 if(allocp == NULL) {
138 allocp = (void*)0x200000; //this is where memory should start
139 allocp->s.next = allocp;
140 allocp->s.size = (0x1400000/sizeof(Block)); //I am going to limit the heap to 20MB for now
141 }
142 prev = allocp; 143 prev = allocp;
143 for(cur = prev->s.next;; ) { 144 for(cur = prev->next;; prev = cur, cur = cur->next) {
144 if(cur->s.size >= nBlocks) { //this section is pretty much exactly copied from K&R 145 if(cur->size >= nUnits) {
145 if(cur->s.size == nBlocks) { 146 if(cur->size == nUnits) {
146 prev->s.next = cur->s.next; 147 prev->next = cur->next;
147 } else { 148 } else {
148 cur->s.size -= nBlocks; 149 temp = cur + nUnits;
149 cur += cur->s.size; 150 temp->size = cur->size - nUnits;
150 cur->s.size = nBlocks; 151 temp->next = cur->next;
152 prev->next = temp;
153 cur->size = nUnits;
151 } 154 }
152 allocp = prev; 155 allocp = prev;
153 return (void*)(cur + 1); 156 return (void*)(cur + 1);
154 } else if(cur == allocp) { //We went back to the start... 157 } else if(cur == allocp) { //We went back to the start...
155 return NULL; 158 return NULL;