realloc.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. __malloc_lock ();
  36. ext_size = __heap_alloc_at (&__malloc_heap, ext_addr, ext_size);
  37. __malloc_unlock ();
  38. if (! ext_size)
  39. /* Our attempts to extend MEM in place failed, just
  40. allocate-and-copy. */
  41. {
  42. new_mem = malloc (new_size);
  43. if (new_mem)
  44. {
  45. memcpy (new_mem, mem, size);
  46. free (mem);
  47. }
  48. }
  49. if (new_mem)
  50. MALLOC_DEBUG (" realloc: returning 0x%lx"
  51. " (base:0x%lx, total_size:%d)\n",
  52. (long)new_mem, (long)new_mem - sizeof(size_t), size);
  53. return new_mem;
  54. }
  55. }
  56. }