Mercurial > sos > sos
diff src/std.c @ 24:45a80ea314ae
The stack now theroretically is a properly working stack!
I added the free function
I converted the code for the stack so that it uses a linked list to store the
stack values.
TODO: create a way to destroy stacks.
author | Jonathan Pevarnek <pevarnj@gmail.com> |
---|---|
date | Wed, 16 Mar 2011 12:00:43 -0400 |
parents | f68b59af5ea6 |
children | c1ad124f2aaf |
line wrap: on
line diff
--- a/src/std.c Wed Mar 16 00:47:21 2011 -0400 +++ b/src/std.c Wed Mar 16 12:00:43 2011 -0400 @@ -126,27 +126,35 @@ return ret; } -static Block *allocp = NULL; //the location of the last item allocated by malloc +static Header base; +static Header *allocp = NULL; //the location of the last known free block void malloc_init(size_t memSize) { - allocp = (void*)HEAP_START; - allocp->next = allocp; - allocp->size = memSize/sizeof(u64); + allocp = &base; + allocp->size = 0; + allocp->next = (void*)HEAP_START; + allocp->next->next = &base; + allocp->next->size = memSize/sizeof(blockUnit); + if((sizeof(blockUnit)%sizeof(u64))) { + sPrint("WARNING: MEMORY NOT 8-BYTE ALIGNED\n"); + char foo[40]; + sPrint(append("MEMORY BLOCK SIZE IS: ", append(itoa(sizeof(Header), foo), "\n"))); + } } void* malloc(size_t size) { - unsigned int nUnits = ((size + sizeof(Block)) + sizeof(u64) - 1)/sizeof(u64); - Block *cur, *prev, *temp; if(allocp == NULL) return NULL; - prev = allocp; + size_t nUnits = ((size + sizeof(Header)) + sizeof(blockUnit) - 1)/sizeof(blockUnit); + Header *prev = allocp; + Header *cur, *temp; for(cur = prev->next;; prev = cur, cur = cur->next) { if(cur->size >= nUnits) { if(cur->size == nUnits) { prev->next = cur->next; } else { - temp = cur + nUnits; + temp = cur + nUnits; //This requires sizeof(blockUnit) == sizeof(Header). TODO fix temp->size = cur->size - nUnits; temp->next = cur->next; prev->next = temp; @@ -160,8 +168,21 @@ } } -/* void free(void *ptr) { + Header *toFree = (Header *)ptr - 1; + Header *scan; + for(scan = allocp; !(toFree > scan && toFree < scan->next); scan = scan->next) + if(scan->next < scan && (toFree > scan || toFree < scan->next)) break; + toFree->next = scan->next; + scan->next = toFree; + if(scan + toFree->size == toFree) { + scan->size += toFree->size; + scan->next = toFree->next; + toFree = scan; + } + if(toFree + toFree->size == toFree->next) { + toFree->size += toFree->next->size; + toFree->next = toFree->next->next; + } } -*/