first_fit_on_freelist.c 961 B

12345678910111213141516171819202122232425262728293031
  1. #include "sll/first_fit_on_freelist.h"
  2. #include "block_header.h"
  3. /**
  4. * \details In order to remove a block from a singly linked list, we need to
  5. * keep track of the previous block as well: The previous block must point to
  6. * the current block's next block once the current one is removed.
  7. */
  8. void * first_fit_on_freelist(heap_t *heap, size_t requested_size) {
  9. void *current_block, *previous_block, *ptr;
  10. ptr = NULL;
  11. for(current_block = heap->free_list_head; current_block != NULL;
  12. current_block = get_next(current_block)) {
  13. if(get_size(current_block) >= requested_size) {
  14. if(current_block == heap->free_list_head) {
  15. heap->free_list_head = get_next(current_block);
  16. } else {
  17. set_next(previous_block, get_next(current_block));
  18. }
  19. ptr = current_block;
  20. break;
  21. }
  22. previous_block = current_block;
  23. }
  24. return ptr;
  25. }