custom_malloc.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "custom_malloc.h"
  2. #include "posix_lock.h"
  3. #include "other.h"
  4. #include "sys_alloc.h"
  5. #include "block_header.h"
  6. void * custom_malloc(heap_t* heap, size_t size) {
  7. void *ptr;
  8. int fixed_list_id, i, found;
  9. maptable_node_t *current_maptable_node;
  10. void *current_block, *previous_block;
  11. ptr = NULL;
  12. posix_lock(heap);
  13. fixed_list_id = map_size_to_list(heap, size);
  14. // If a fixed list is found, do a first fit
  15. if(fixed_list_id != -1) {
  16. current_maptable_node = heap->maptable_head;
  17. // traverse through the maptable node list
  18. if(fixed_list_id != 0) {
  19. for(i = 1; i < fixed_list_id; i++) {
  20. current_maptable_node = current_maptable_node->next;
  21. }
  22. }
  23. if(current_maptable_node->fixed_list_head != NULL) {
  24. ptr = current_maptable_node->fixed_list_head;
  25. current_maptable_node->fixed_list_head = get_next(ptr);
  26. set_requested_size(ptr, size);
  27. }
  28. }
  29. if(ptr == NULL) {
  30. found = 0;
  31. // first fit from free list
  32. for(current_block = heap->free_list_head; current_block != NULL; current_block = get_next(current_block)) {
  33. if(get_size(current_block) >= size) {
  34. ptr = current_block;
  35. set_requested_size(ptr, size);
  36. set_next(ptr, heap->used_blocks_head);
  37. heap->used_blocks_head = ptr;
  38. if(current_block != heap->free_list_head) {
  39. set_next(previous_block, get_next(ptr));
  40. } else {
  41. heap->free_list_head = get_next(ptr);
  42. }
  43. posix_unlock(heap);
  44. return ptr;
  45. }
  46. previous_block = current_block;
  47. }
  48. if(!found) {
  49. ptr = sys_alloc(heap, size);
  50. }
  51. }
  52. posix_unlock(heap);
  53. return ptr;
  54. }