1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- #include "custom_malloc.h"
- #include "posix_lock.h"
- #include "other.h"
- #include "sys_alloc.h"
- #include "block_header.h"
- void * custom_malloc(heap_t* heap, size_t size) {
- void *ptr;
- int fixed_list_id, i, found;
- maptable_node_t *current_maptable_node;
- void *current_block, *previous_block;
- ptr = NULL;
- posix_lock(heap);
- fixed_list_id = map_size_to_list(heap, size);
-
- // If a fixed list is found, do a first fit
- if(fixed_list_id != -1) {
- current_maptable_node = heap->maptable_head;
- // traverse through the maptable node list
- if(fixed_list_id != 0) {
- for(i = 1; i < fixed_list_id; i++) {
- current_maptable_node = current_maptable_node->next;
- }
- }
- if(current_maptable_node->fixed_list_head != NULL) {
- ptr = current_maptable_node->fixed_list_head;
- current_maptable_node->fixed_list_head = get_next(ptr);
- set_requested_size(ptr, size);
- }
- }
- if(ptr == NULL) {
- found = 0;
- // first fit from free list
- for(current_block = heap->free_list_head; current_block != NULL; current_block = get_next(current_block)) {
- if(get_size(current_block) >= size) {
- ptr = current_block;
- set_requested_size(ptr, size);
- set_next(ptr, heap->used_blocks_head);
- heap->used_blocks_head = ptr;
- if(current_block != heap->free_list_head) {
- set_next(previous_block, get_next(ptr));
- } else {
- heap->free_list_head = get_next(ptr);
- }
- posix_unlock(heap);
- return ptr;
- }
- previous_block = current_block;
- }
- if(!found) {
- ptr = sys_alloc(heap, size);
- }
- }
- posix_unlock(heap);
- return ptr;
- }
|