heap_alloc.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * libc/stdlib/malloc/heap_alloc.c -- allocate memory from 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. /* Allocate and return a block at least *SIZE bytes long from HEAP.
  16. *SIZE is adjusted to reflect the actual amount allocated (which may be
  17. greater than requested). */
  18. void *
  19. __heap_alloc (struct heap_free_area *heap, size_t *size)
  20. {
  21. struct heap_free_area *fa;
  22. size_t _size = *size;
  23. void *mem = 0;
  24. _size = HEAP_ADJUST_SIZE (_size);
  25. if (_size < sizeof (struct heap_free_area))
  26. /* Because we sometimes must use a freed block to hold a free-area node,
  27. we must make sure that every allocated block can hold one. */
  28. _size = HEAP_ADJUST_SIZE (sizeof (struct heap_free_area));
  29. HEAP_DEBUG (heap, "before __heap_alloc");
  30. /* Look for a free area that can contain _SIZE bytes. */
  31. for (fa = heap; fa; fa = fa->next)
  32. if (fa->size >= _size)
  33. {
  34. /* Found one! */
  35. mem = HEAP_FREE_AREA_START (fa);
  36. *size = __heap_free_area_alloc (heap, fa, _size);
  37. break;
  38. }
  39. HEAP_DEBUG (heap, "after __heap_alloc");
  40. return mem;
  41. }