custom_malloc.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <stdio.h>
  2. #include "custom_malloc.h"
  3. #include "posix_lock.h"
  4. #include "other.h"
  5. #include "sys_alloc.h"
  6. #include "block_header.h"
  7. void * custom_malloc(heap_t* heap, size_t size) {
  8. void *ptr;
  9. int fixed_list_id, i, found;
  10. maptable_node_t *current_maptable_node;
  11. void *current_block, *previous_block;
  12. ptr = NULL;
  13. previous_block = NULL;
  14. posix_lock(heap);
  15. printf("Searching for a free block of size %d.\n", size);
  16. fixed_list_id = map_size_to_list(heap, size);
  17. // If a fixed list is found, do a first fit
  18. if(fixed_list_id != -1) {
  19. printf("Searching on fixed lists...\n");
  20. current_maptable_node = heap->maptable_head;
  21. // traverse through the maptable node list
  22. if(fixed_list_id != 0) {
  23. for(i = 1; i < fixed_list_id; i++) {
  24. current_maptable_node = current_maptable_node->next;
  25. }
  26. }
  27. if(current_maptable_node->fixed_list_head != NULL) {
  28. ptr = current_maptable_node->fixed_list_head;
  29. current_maptable_node->fixed_list_head = get_next(ptr);
  30. set_requested_size(ptr, size);
  31. set_next(ptr, heap->used_blocks_head);
  32. heap->used_blocks_head = ptr;
  33. }
  34. }
  35. if(ptr == NULL) {
  36. found = 0;
  37. // first fit from free list
  38. printf("Searching on the free list...\n", size);
  39. for(current_block = heap->free_list_head; current_block != NULL; current_block = get_next(current_block)) {
  40. if(get_size(current_block) >= size) {
  41. ptr = current_block;
  42. set_requested_size(ptr, size);
  43. set_next(ptr, heap->used_blocks_head);
  44. heap->used_blocks_head = ptr;
  45. if(current_block != heap->free_list_head) {
  46. set_next(previous_block, get_next(ptr));
  47. } else {
  48. heap->free_list_head = get_next(ptr);
  49. }
  50. posix_unlock(heap);
  51. printf("Block found in the free list.\n");
  52. return ptr;
  53. }
  54. previous_block = current_block;
  55. }
  56. if(!found) {
  57. printf("No free available chunk was found.\n");
  58. ptr = sys_alloc(heap, size);
  59. printf("Chuck was given by the OS.\n");
  60. }
  61. }
  62. posix_unlock(heap);
  63. return ptr;
  64. }