realloc.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 <errno.h>
  16. #include "malloc.h"
  17. #include "heap.h"
  18. void *
  19. realloc (void *mem, size_t new_size)
  20. {
  21. size_t size;
  22. char *base_mem;
  23. /* Check for special cases. */
  24. if (!mem)
  25. return malloc(new_size);
  26. if (!new_size) {
  27. free (mem);
  28. return (malloc(new_size));
  29. }
  30. /* Normal realloc. */
  31. base_mem = MALLOC_BASE (mem);
  32. size = MALLOC_SIZE (mem);
  33. /* Include extra space to record the size of the allocated block.
  34. Also make sure that we're dealing in a multiple of the heap
  35. allocation unit (SIZE is already guaranteed to be so).*/
  36. new_size = HEAP_ADJUST_SIZE (new_size + MALLOC_HEADER_SIZE);
  37. MALLOC_DEBUG (1, "realloc: 0x%lx, %d (base = 0x%lx, total_size = %d)",
  38. (long)mem, new_size, (long)base_mem, size);
  39. if (new_size > size)
  40. /* Grow the block. */
  41. {
  42. size_t extra = new_size - size;
  43. __heap_lock (&__malloc_heap);
  44. extra = __heap_alloc_at (&__malloc_heap, base_mem + size, extra);
  45. __heap_unlock (&__malloc_heap);
  46. if (extra)
  47. /* Record the changed size. */
  48. MALLOC_SET_SIZE (base_mem, size + extra);
  49. else
  50. /* Our attempts to extend MEM in place failed, just
  51. allocate-and-copy. */
  52. {
  53. void *new_mem = malloc (new_size - MALLOC_HEADER_SIZE);
  54. if (new_mem)
  55. {
  56. memcpy (new_mem, mem, size - MALLOC_HEADER_SIZE);
  57. free (mem);
  58. }
  59. mem = new_mem;
  60. }
  61. }
  62. else if (new_size + MALLOC_REALLOC_MIN_FREE_SIZE <= size)
  63. /* Shrink the block. */
  64. {
  65. __heap_lock (&__malloc_heap);
  66. __heap_free (&__malloc_heap, base_mem + new_size, size - new_size);
  67. __heap_unlock (&__malloc_heap);
  68. MALLOC_SET_SIZE (base_mem, new_size);
  69. }
  70. if (mem)
  71. MALLOC_DEBUG (-1, "realloc: returning 0x%lx (base:0x%lx, total_size:%d)",
  72. (long)mem, (long)MALLOC_BASE(mem), (long)MALLOC_SIZE(mem));
  73. else
  74. MALLOC_DEBUG (-1, "realloc: returning 0");
  75. return mem;
  76. }