heap_free.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * libc/stdlib/malloc/heap_free.c -- return memory to a heap
  3. *
  4. * Copyright (C) 2002 NEC Corporation
  5. * Copyright (C) 2002 Miles Bader <miles@gnu.org>
  6. *
  7. * This file is subject to the terms and conditions of the GNU Lesser
  8. * General Public License. See the file COPYING.LIB in the main
  9. * directory of this archive for more details.
  10. *
  11. * Written by Miles Bader <miles@gnu.org>
  12. */
  13. #include <stdlib.h>
  14. #include "heap.h"
  15. /* Return the memory area MEM of size SIZE to HEAP. */
  16. struct heap_free_area *
  17. __heap_free (struct heap *heap, void *mem, size_t size)
  18. {
  19. struct heap_free_area *prev_fa, *fa;
  20. void *end = (char *)mem + size;
  21. HEAP_DEBUG (heap, "before __heap_free");
  22. /* Find an adjacent free-list entry. */
  23. for (prev_fa = 0, fa = heap->free_areas; fa; prev_fa = fa, fa = fa->next)
  24. {
  25. size_t fa_size = fa->size;
  26. void *fa_mem = HEAP_FREE_AREA_START (fa);
  27. if (fa_mem > end)
  28. /* We've reached the right spot in the free-list without finding an
  29. adjacent free-area, so continue below to add a new free area. */
  30. break;
  31. else if (fa_mem == end)
  32. /* FA is just after MEM, grow down to encompass it. */
  33. {
  34. fa_size += size;
  35. /* See if FA can now be merged with its predecessor. */
  36. if (prev_fa && mem == HEAP_FREE_AREA_END (prev_fa))
  37. /* Yup; merge PREV_FA's info into FA. */
  38. {
  39. fa_size += prev_fa->size;
  40. __heap_link_free_area_after (heap, fa, prev_fa->prev);
  41. }
  42. fa->size = fa_size;
  43. goto done;
  44. }
  45. else if (HEAP_FREE_AREA_END (fa) == mem)
  46. /* FA is just before MEM, expand to encompass it. */
  47. {
  48. struct heap_free_area *next_fa = fa->next;
  49. fa_size += size;
  50. /* See if FA can now be merged with its successor. */
  51. if (next_fa && end == HEAP_FREE_AREA_START (next_fa))
  52. /* Yup; merge FA's info into NEXT_FA. */
  53. {
  54. fa_size += next_fa->size;
  55. __heap_link_free_area_after (heap, next_fa, prev_fa);
  56. fa = next_fa;
  57. }
  58. else
  59. /* FA can't be merged; move the descriptor for it to the tail-end
  60. of the memory block. */
  61. {
  62. /* The new descriptor is at the end of the extended block,
  63. SIZE bytes later than the old descriptor. */
  64. fa = (struct heap_free_area *)((char *)fa + size);
  65. /* Update links with the neighbors in the list. */
  66. __heap_link_free_area (heap, fa, prev_fa, next_fa);
  67. }
  68. fa->size = fa_size;
  69. goto done;
  70. }
  71. }
  72. /* Make MEM into a new free-list entry. */
  73. fa = __heap_add_free_area (heap, mem, size, prev_fa, fa);
  74. done:
  75. HEAP_DEBUG (heap, "after __heap_free");
  76. return fa;
  77. }