realloc.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. void *base_mem = mem - MALLOC_ALIGNMENT;
  25. size_t size = *(size_t *)base_mem;
  26. MALLOC_DEBUG ("realloc: 0x%lx, %d (base = 0x%lx, total_size = %d)\n",
  27. (long)mem, new_size, (long)base_mem, size);
  28. if (new_size <= size)
  29. return mem;
  30. else
  31. {
  32. void *new_mem = 0;
  33. size_t ext_size = new_size - size;
  34. void *ext_addr = (char *)base_mem + ext_size;
  35. ext_size = __heap_alloc_at (&__malloc_heap, ext_addr, ext_size);
  36. if (! ext_size)
  37. /* Our attempts to extend MEM in place failed, just
  38. allocate-and-copy. */
  39. {
  40. new_mem = malloc (new_size);
  41. if (new_mem)
  42. {
  43. memcpy (new_mem, mem, size);
  44. free (mem);
  45. }
  46. }
  47. if (new_mem)
  48. MALLOC_DEBUG (" realloc: returning 0x%lx"
  49. " (base:0x%lx, total_size:%d)\n",
  50. (long)new_mem, (long)new_mem - sizeof(size_t), size);
  51. return new_mem;
  52. }
  53. }
  54. }