yuezonghe | 824eb0c | 2024-06-27 02:32:26 -0700 | [diff] [blame^] | 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 | |
| 14 | #include <stdlib.h> |
| 15 | |
| 16 | #include "heap.h" |
| 17 | |
| 18 | |
| 19 | /* Allocate and return a block at least *SIZE bytes long from HEAP. |
| 20 | *SIZE is adjusted to reflect the actual amount allocated (which may be |
| 21 | greater than requested). */ |
| 22 | void * |
| 23 | __heap_alloc (struct heap_free_area **heap, size_t *size) |
| 24 | { |
| 25 | struct heap_free_area *fa; |
| 26 | size_t _size = *size; |
| 27 | void *mem = 0; |
| 28 | |
| 29 | _size = HEAP_ADJUST_SIZE (_size); |
| 30 | |
| 31 | if (_size < sizeof (struct heap_free_area)) |
| 32 | /* Because we sometimes must use a freed block to hold a free-area node, |
| 33 | we must make sure that every allocated block can hold one. */ |
| 34 | _size = HEAP_ADJUST_SIZE (sizeof (struct heap_free_area)); |
| 35 | |
| 36 | HEAP_DEBUG (*heap, "before __heap_alloc"); |
| 37 | |
| 38 | /* Look for a free area that can contain _SIZE bytes. */ |
| 39 | for (fa = *heap; fa; fa = fa->next) |
| 40 | if (fa->size >= _size) |
| 41 | { |
| 42 | /* Found one! */ |
| 43 | mem = HEAP_FREE_AREA_START (fa); |
| 44 | *size = __heap_free_area_alloc (heap, fa, _size); |
| 45 | break; |
| 46 | } |
| 47 | |
| 48 | HEAP_DEBUG (*heap, "after __heap_alloc"); |
| 49 | |
| 50 | return mem; |
| 51 | } |