Browse Source

Fixed a major bug involving and pointers

tree_alloc
Thomas Johnson 1 year ago
parent
commit
4473209226
  1. 6
      main.c
  2. 41
      tree_alloc.c

6
main.c

@ -68,8 +68,9 @@ int validate_record(struct AllocationRecord *record) {
}
void new_region(struct AllocationRecord *dummy, struct Arena *arena) {
int size = 1 + (rand() % 8192);
int align = 1 << (rand() % 4);
uintptr_t size = 1 + (rand() % 8192);
uintptr_t align = 1 << (rand() % 4);
printf("alloc'ing a region of size %lu with alignment %lu, id %i\n", size, align, dummy->id);
void *region = alloc(arena, size, align);
if (region == NULL) {
printf("memory allocator broke, we have 1L though\n");
@ -87,6 +88,7 @@ void delete_region(struct AllocationRecord *dummy, struct Arena *arena) {
}
uintptr_t which = rand() % dummy->size;
struct AllocationRecord *zap = get_record(dummy, which);
printf("dealloc'ing a region of size %lu, id %i\n", zap->size, zap->id);
unalloc(arena, zap->allocation);
delete_record(dummy, zap);
}

41
tree_alloc.c

@ -80,6 +80,34 @@ TreeAlloc *search_by_size(TreeAlloc *root, uintptr_t padding, uintptr_t align, u
}
}
TreeAlloc *succ(TreeAlloc *el) {
if (el->right != NULL) {
el = el->right;
while (el->left != NULL) {
el = el->left;
}
return el;
}
while (el->parent != NULL && el == el->parent->right) {
el = el->parent;
}
return el->parent;
}
TreeAlloc *pred(TreeAlloc *el) {
if (el->left != NULL) {
el = el->left;
while (el->right != NULL) {
el = el->right;
}
return el;
}
while (el->parent != NULL && el == el->parent->left) {
el = el->parent;
}
return el->parent;
}
TreeAlloc *get_sibling(TreeAlloc *ta) {
TreeAlloc *p = ta->parent;
if (!p)
@ -437,6 +465,19 @@ void *alloc(Arena *arena, uintptr_t size, uintptr_t align) {
FreeSpace *insert_point = (FreeSpace*) search_by_size((TreeAlloc*) arena->root_freespace, 0, 1, new_free_size);
insert_left((TreeAlloc**) &arena->root_freespace, (TreeAlloc*) new_free, (TreeAlloc*) insert_point);
}
// Set the region following this one to be the new free space
region->after = (TreeAlloc*) new_free;
} else {
// There isn't a free space after this one, so put the `next` pointer at the next allocated
// region.
region->after = succ(region);
}
// Also make sure the `before` pointer is correct.
TreeAlloc *before_alloc = pred(region);
if (before_alloc == NULL || ((void*) before_alloc) + before_alloc->size < (void*) region) {
region->before = search_by_address((TreeAlloc*) arena->root_freespace, region);
} else {
region->before = before_alloc;
}
return align_after(region + sizeof(TreeAlloc), actual_align);
}

Loading…
Cancel
Save