diff src/std.c @ 21:7c2adb65ceac

Started working on dynamic memory I have a slightly adapted version of dynamic memory allocation from the H&R book in the program now, I will soon be adding the free function. I fixed sPrint so it will work with large buffers.
author Jonathan Pevarnek <pevarnj@gmail.com>
date Tue, 15 Mar 2011 22:55:36 -0400
parents 525eab23e68a
children 3fb0ec050ff3
line wrap: on
line diff
--- a/src/std.c	Mon Mar 14 15:06:11 2011 -0400
+++ b/src/std.c	Tue Mar 15 22:55:36 2011 -0400
@@ -86,7 +86,10 @@
 {
 	char *b = a;
 	while(*b && *++b);
-	putline(a, b - a);
+	do {
+		putline(a, (b - a > CON_LEN)?CON_LEN:(b - a));
+		a += CON_LEN;
+	} while(a < b);
 }
 
 int strcmp(const char *a, const char *b)
@@ -122,3 +125,40 @@
 	while((*dest++ = *src++));
 	return ret;
 }
+
+static Block *allocp = NULL; //the location of the last item allocated by malloc
+
+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
+	}
+	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;
+			} else {
+				cur->s.size -= nBlocks;
+				cur += cur->s.size;
+				cur->s.size = nBlocks;
+			}
+			allocp = prev;
+			return (void*)(cur + 1);
+		} else if(cur == allocp) { //We went back to the start...
+			return NULL;
+		}
+	}
+}
+
+/*
+void free(void *ptr)
+{
+}
+*/