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. size_t extra = new_size - size;
  35. __malloc_lock ();
  36. extra = __heap_alloc_at (&__malloc_heap, base_mem + size, extra);
  37. __malloc_unlock ();
  38. if (extra)
  39. /* Record the changed size. */
  40. MALLOC_SET_SIZE (mem, new_size);
  41. else
  42. /* Our attempts to extend MEM in place failed, just
  43. allocate-and-copy. */
  44. {
  45. void *new_mem = malloc (new_size);
  46. if (new_mem)
  47. {
  48. memcpy (new_mem, mem, size);
  49. free (mem);
  50. }
  51. mem = new_mem;
  52. }
  53. }
  54. else if (new_size + HEAP_MIN_FREE_AREA_SIZE <= size)
  55. /* Shrink the block. */
  56. {
  57. __malloc_lock ();
  58. __heap_free (&__malloc_heap, base_mem + new_size, size - new_size);
  59. __malloc_unlock ();
  60. MALLOC_SET_SIZE (mem, new_size);
  61. }
  62. if (mem)
  63. MALLOC_DEBUG (" realloc: returning 0x%lx"
  64. " (base:0x%lx, total_size:%d)\n",
  65. (long)new_mem, (long)new_mem - sizeof(size_t), size);
  66. return mem;
  67. }
  68. }