fixed malloc
authorJohn Tsiombikas <nuclear@member.fsf.org>
Fri, 23 Aug 2024 02:52:27 +0000 (05:52 +0300)
committerJohn Tsiombikas <nuclear@member.fsf.org>
Fri, 23 Aug 2024 02:52:27 +0000 (05:52 +0300)
kern/src/libc/malloc.c
kern/src/main.c

index 31bb294..cac7500 100644 (file)
@@ -126,11 +126,13 @@ void kfree(void __far *p)
        }
 
        cur = pool;
+       curend = RNGEND(cur);
        last = 0;
-       while(cur && mem > (curend = RNGEND(cur))) {
+       while(cur && mem > curend) {
                assert_magic(cur, MAGIC_FREE);
                last = cur;
                cur = cur->next;
+               curend = RNGEND(cur);
        }
 
        if(!cur) {
@@ -143,11 +145,16 @@ void kfree(void __far *p)
                return;
        }
 
+       if(last && RNGEND(last) < mem && memend < cur) {
+               /* not adjacent to anything, insert between last and cur */
+               mem->prev = last;
+               mem->next = cur;
+               last->next = mem;
+               cur->prev = mem;
+       }
+
        if(curend == mem) {
                /* memory adjacent at the end of previous range */
-               mem->next = cur->next;
-               mem->prev = cur;
-               cur->next = mem;
                cur->len += mem->len;
                mem->magic = 0;
                mem = cur;      /* fall through to check adjacency at the other end */
index ab6f0f8..6fc49f6 100644 (file)
@@ -37,8 +37,11 @@ void kmain(void)
        dbg_print_kmalloc_stats();
        dbg_print_kmalloc_pool();
 
-       for(i=0; i<40; i++) {
+       for(i=0; i<32; i++) {
                int idx = rand() & 0x1f;
+               while(!ptr[idx]) {
+                       idx = (idx + 1) & 0x1f;
+               }
                if(ptr[idx]) {
                        printf("FREE(%x:%x)\n", FP_SEG(ptr[idx]), FP_OFFS(ptr[idx]));
                        kfree(ptr[idx]);