custom_malloc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. previous_block = NULL;
  13. posix_lock(heap);
  14. fixed_list_id = map_size_to_list(heap, size);
  15. // If a fixed list is found, do a first fit
  16. if(fixed_list_id != -1) {
  17. current_maptable_node = heap->maptable_head;
  18. // traverse through the maptable node list
  19. if(fixed_list_id != 0) {
  20. for(i = 1; i < fixed_list_id; i++) {
  21. current_maptable_node = current_maptable_node->next;
  22. }
  23. }
  24. if(current_maptable_node->fixed_list_head != NULL) {
  25. ptr = current_maptable_node->fixed_list_head;
  26. current_maptable_node->fixed_list_head = get_next(ptr);
  27. set_requested_size(ptr, size);
  28. set_next(ptr, heap->used_blocks_head);
  29. heap->used_blocks_head = ptr;
  30. }
  31. }
  32. if(ptr == NULL) {
  33. found = 0;
  34. // first fit from free list
  35. for(current_block = heap->free_list_head; current_block != NULL;
  36. current_block = get_next(current_block)) {
  37. if(get_size(current_block) >= size) {
  38. ptr = current_block;
  39. heap->used_blocks_head = ptr;
  40. if(current_block != heap->free_list_head) {
  41. set_next(previous_block, get_next(ptr));
  42. } else {
  43. heap->free_list_head = get_next(ptr);
  44. }
  45. set_requested_size(ptr, size);
  46. set_next(ptr, heap->used_blocks_head);
  47. // Begin of Stats
  48. heap->dmm_stats.live_objects += 1;
  49. heap->dmm_stats.num_malloc += 1;
  50. // End of Stats
  51. posix_unlock(heap);
  52. return ptr;
  53. }
  54. previous_block = current_block;
  55. }
  56. if(!found) {
  57. ptr = sys_alloc(heap, size);
  58. heap->dmm_stats.mem_allocated += req_padding(size);
  59. heap->dmm_stats.mem_requested += size;
  60. }
  61. }
  62. // Begin of Stats
  63. heap->dmm_stats.live_objects += 1;
  64. heap->dmm_stats.num_malloc += 1;
  65. // End of Stats
  66. posix_unlock(heap);
  67. return ptr;
  68. }