[crt] Set the default heap. Update next_offset after blocks have been merged.
authorcoderain <coderain@sdf.org>
Wed, 15 Nov 2017 04:22:53 +0000 (05:22 +0100)
committercoderain <coderain@sdf.org>
Wed, 15 Nov 2017 04:22:53 +0000 (05:22 +0100)
crt/src/malloc.c

index 30fa14296d43094744561913492032d346f11d8d..5d09e0ccd3f2db4d539bdec1edd27534590dbad0 100644 (file)
@@ -43,6 +43,11 @@ static void __crt_heap_coalesce(__crt_heap_t *heap)
 
         if (previous && !(previous->flags & ALLOCATED) && !(ptr->flags & ALLOCATED))
         {
+            if (((uintptr_t)ptr - (uintptr_t)heap->base) == heap->next_offset)
+            {
+                heap->next_offset = (uintptr_t)previous - (uintptr_t)heap->base;
+            }
+
             previous->size += ptr->size + sizeof(heap_header_t);
         }
         else
@@ -110,6 +115,11 @@ void *__crt_heap_realloc(__crt_heap_t *heap, void *ptr, size_t alignment, size_t
 
              if (!(next->flags & ALLOCATED) && (header->size + next->size + sizeof(heap_header_t)) >= size)
              {
+                 if (((uintptr_t)next - (uintptr_t)heap->base) == heap->next_offset)
+                 {
+                     heap->next_offset = (uintptr_t)header - (uintptr_t)heap->base;
+                 }
+
                  header->size += next->size + sizeof(heap_header_t);
                  if (heap->flags & __CRT_HEAP_FLAG_ZEROFILL) memset(next, 0, size - header->size - size);
              }
@@ -378,5 +388,6 @@ int __crt_initialize_heap(void)
     status = syscall_alloc_memory(INVALID_HANDLE, &heap.base, heap.size, MEMORY_BLOCK_ACCESSIBLE | MEMORY_BLOCK_WRITABLE);
     if (status != ERR_SUCCESS) return -1;
 
+    __crt_default_heap = &heap;
     return 0;
 }