custom_malloc.c 1.5 KB

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