Browse Source

Merge branch 'tree_alloc' of gitea:cameron/cs241-project into tree_alloc

Cameron Weinfurt 1 year ago
parent
commit
2c6fcbe9fa
1 changed files with 44 additions and 1 deletions
  1. 44
    1
      tree_alloc.c

+ 44
- 1
tree_alloc.c View File

@@ -209,11 +209,54 @@ void insert_left(TreeAlloc** root_ptr, TreeAlloc* to_insert, TreeAlloc* before)
209 209
 	repair_tree_after_insert(to_insert);
210 210
 }
211 211
 
212
-void *unalloc(Arena *arena, void *addr) {
212
+void unalloc(Arena *arena, void *addr) {
213 213
   if (arena->root_treealloc == NULL) {
214 214
     arena->error("attempt to unallocate when there are no allocations!");
215
+    return;
215 216
   }
217
+  // Find the node this address belongs to
216 218
   TreeAlloc *node = search_by_address(arena->root_treealloc, addr);
219
+  if (node == NULL) {
220
+    arena->error("attempt to free memory outside any allocations!");
221
+    return;
222
+  }
223
+  // Handle the watermark allocator in this region
224
+  if (node->type == RT_WATERMARK) {
225
+    // TODO: handle watermark deallocation
226
+    return;
227
+  }
228
+  // Get rid of it
229
+  remove_node(&arena->root_treealloc, node);
230
+  // If there's free space on either side of it, merge it with the free space into a bigger chunk of
231
+  // free space.
232
+  uintptr_t size = node->size;
233
+  FreeSpace *start = (FreeSpace*) node;
234
+  if (node->before != NULL && node->before->type == RT_FREESPACE) {
235
+    start = (FreeSpace*) node->before;
236
+    size += node->before->size;
237
+    remove_node((TreeAlloc**) &arena->root_freespace, node->before);
238
+  }
239
+  if (node->after != NULL && node->after->type == RT_FREESPACE) {
240
+    size += node->after->size;
241
+    remove_node((TreeAlloc**) &arena->root_freespace, node->after);
242
+  }
243
+  start->type = RT_FREESPACE;
244
+  start->size = size;
245
+  // And finally, insert the resulting free space.
246
+  if (arena->root_freespace == NULL) {
247
+    insert_singleton((TreeAlloc**) &arena->root_freespace, (TreeAlloc*) start);
248
+  } else {
249
+    TreeAlloc *insert_point = search_by_size((TreeAlloc*) arena->root_freespace, 0, 1, size);
250
+    if (insert_point == NULL) {
251
+      TreeAlloc *head = (TreeAlloc*) arena->root_freespace;
252
+      while (head->right != NULL) {
253
+        head = head->right;
254
+      }
255
+      insert_right((TreeAlloc**) &arena->root_freespace, (TreeAlloc*) start, head);
256
+    } else {
257
+      insert_left((TreeAlloc**) &arena->root_freespace, (TreeAlloc*) start, insert_point);
258
+    }
259
+  }
217 260
   // TODO
218 261
 }
219 262
 

Loading…
Cancel
Save