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 (end == fa_mem)
  28. /* FA is just after MEM, grow down to encompass it. */
  29. {
  30. fa_size += size;
  31. /* See if FA can now be merged with its predecessor. */
  32. if (prev_fa && fa_mem - size == HEAP_FREE_AREA_END (prev_fa))
  33. /* Yup; merge PREV_FA's info into FA. */
  34. {
  35. fa_size += prev_fa->size;
  36. __heap_link_free_area_after (heap, fa, prev_fa->prev);
  37. }
  38. fa->size = fa_size;
  39. goto done;
  40. }
  41. else if (HEAP_FREE_AREA_END (fa) == mem)
  42. /* FA is just before MEM, expand to encompass it. */
  43. {
  44. struct heap_free_area *next_fa = fa->next;
  45. fa_size += size;
  46. /* See if FA can now be merged with its successor. */
  47. if (next_fa && mem + size == HEAP_FREE_AREA_START (next_fa))
  48. /* Yup; merge FA's info into NEXT_FA. */
  49. {
  50. fa_size += next_fa->size;
  51. __heap_link_free_area_after (heap, next_fa, prev_fa);
  52. fa = next_fa;
  53. }
  54. else
  55. /* FA can't be merged; move the descriptor for it to the tail-end
  56. of the memory block. */
  57. {
  58. /* The new descriptor is at the end of the extended block,
  59. SIZE bytes later than the old descriptor. */
  60. fa = (struct heap_free_area *)((char *)fa + size);
  61. /* Update links with the neighbors in the list. */
  62. __heap_link_free_area (heap, fa, prev_fa, next_fa);
  63. }
  64. fa->size = fa_size;
  65. goto done;
  66. }
  67. else if (fa_mem > mem)
  68. /* We've reached the right spot in the free-list without finding an
  69. adjacent free-area, so continue below to add a new free area. */
  70. break;
  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. }