diff 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
line wrap: on
line diff
--- a/src/std.c	Tue Mar 15 22:55:36 2011 -0400
+++ b/src/std.c	Wed Mar 16 00:09:35 2011 -0400
@@ -128,26 +128,29 @@
 
 static Block *allocp = NULL; //the location of the last item allocated by malloc
 
+void malloc_init(size_t memSize)
+{
+	allocp = (void*)0x200000;
+	allocp->next = allocp;
+	allocp->size = memSize/sizeof(u64);
+}
+
 void* malloc(size_t size)
 {
-	unsigned int nBlocks = 1 + (size + sizeof(Block) - 1)/sizeof(Block);
-	//We are allocating a number of blocks equal to the number needed rounded up
-	//plus one for the actual info block
-	Block *cur, *prev;
-	if(allocp == NULL) {
-		allocp = (void*)0x200000; //this is where memory should start
-		allocp->s.next = allocp;
-		allocp->s.size = (0x1400000/sizeof(Block)); //I am going to limit the heap to 20MB for now
-	}
+	unsigned int nUnits = ((size + sizeof(Block)) + sizeof(u64) - 1)/sizeof(u64);
+	Block *cur, *prev, *temp;
+	if(allocp == NULL) return NULL;
 	prev = allocp;
-	for(cur = prev->s.next;; ) {
-		if(cur->s.size >= nBlocks) { //this section is pretty much exactly copied from K&R
-			if(cur->s.size == nBlocks) {
-				prev->s.next = cur->s.next;
+	for(cur = prev->next;; prev = cur, cur = cur->next) {
+		if(cur->size >= nUnits) {
+			if(cur->size == nUnits) {
+				prev->next = cur->next;
 			} else {
-				cur->s.size -= nBlocks;
-				cur += cur->s.size;
-				cur->s.size = nBlocks;
+				temp = cur + nUnits;
+				temp->size = cur->size - nUnits;
+				temp->next = cur->next;
+				prev->next = temp;
+				cur->size = nUnits;
 			}
 			allocp = prev;
 			return (void*)(cur + 1);