realloc.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * libc/stdlib/malloc/realloc.c -- realloc function
  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 <string.h>
  15. #include "malloc.h"
  16. #include "heap.h"
  17. void *
  18. realloc (void *mem, size_t new_size)
  19. {
  20. if (! mem)
  21. return malloc (new_size);
  22. else
  23. {
  24. char *base_mem = MALLOC_BASE (mem);
  25. size_t size = MALLOC_SIZE (mem);
  26. /* Make sure that we're dealing in a multiple of the heap allocation
  27. unit (SIZE is already guaranteed to be so). */
  28. // new_size = HEAP_ADJUST_SIZE (new_size);
  29. MALLOC_DEBUG ("realloc: 0x%lx, %d (base = 0x%lx, total_size = %d)\n",
  30. (long)mem, new_size, (long)base_mem, size);
  31. if (new_size > size)
  32. /* Grow the block. */
  33. {
  34. void *new_mem = 0;
  35. size_t ext_size = new_size - size;
  36. void *ext_addr = base_mem + size;
  37. __malloc_lock ();
  38. ext_size = __heap_alloc_at (&__malloc_heap, ext_addr, ext_size);
  39. __malloc_unlock ();
  40. if (! ext_size)
  41. /* Our attempts to extend MEM in place failed, just
  42. allocate-and-copy. */
  43. {
  44. new_mem = malloc (new_size);
  45. if (new_mem)
  46. {
  47. memcpy (new_mem, mem, size);
  48. free (mem);
  49. }
  50. }
  51. if (new_mem)
  52. MALLOC_DEBUG (" realloc: returning 0x%lx"
  53. " (base:0x%lx, total_size:%d)\n",
  54. (long)new_mem, (long)new_mem - sizeof(size_t), size);
  55. return new_mem;
  56. }
  57. else if (new_size + HEAP_MIN_FREE_AREA_SIZE <= size)
  58. /* Shrink the block. */
  59. {
  60. __malloc_lock ();
  61. __heap_free (&__malloc_heap, base_mem + new_size, new_size - size);
  62. __malloc_unlock ();
  63. }
  64. else
  65. /* Do nothing. */
  66. return mem;
  67. }
  68. }