123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include "malloc.h"
- #include "heap.h"
- void *
- realloc (void *mem, size_t new_size)
- {
- size_t size;
- char *base_mem;
- if (! mem)
- return malloc (new_size);
-
- if (! new_size)
- {
- free (mem);
- return NULL;
- }
-
- if (unlikely(((unsigned long)new_size > (unsigned long)(MALLOC_HEADER_SIZE*-2))))
- return NULL;
-
- base_mem = MALLOC_BASE (mem);
- size = MALLOC_SIZE (mem);
-
- new_size = HEAP_ADJUST_SIZE (new_size + MALLOC_HEADER_SIZE);
- if (new_size < sizeof (struct heap_free_area))
-
- new_size = HEAP_ADJUST_SIZE (sizeof (struct heap_free_area));
- MALLOC_DEBUG (1, "realloc: 0x%lx, %d (base = 0x%lx, total_size = %d)",
- (long)mem, new_size, (long)base_mem, size);
- if (new_size > size)
-
- {
- size_t extra = new_size - size;
- __heap_lock (&__malloc_heap_lock);
- extra = __heap_alloc_at (&__malloc_heap, base_mem + size, extra);
- __heap_unlock (&__malloc_heap_lock);
- if (extra)
-
- MALLOC_SET_SIZE (base_mem, size + extra);
- else
-
- {
- void *new_mem = malloc (new_size - MALLOC_HEADER_SIZE);
- if (new_mem)
- {
- memcpy (new_mem, mem, size - MALLOC_HEADER_SIZE);
- free (mem);
- }
- mem = new_mem;
- }
- }
- else if (new_size + MALLOC_REALLOC_MIN_FREE_SIZE <= size)
-
- {
- __heap_lock (&__malloc_heap_lock);
- __heap_free (&__malloc_heap, base_mem + new_size, size - new_size);
- __heap_unlock (&__malloc_heap_lock);
- MALLOC_SET_SIZE (base_mem, new_size);
- }
- if (mem)
- MALLOC_DEBUG (-1, "realloc: returning 0x%lx (base:0x%lx, total_size:%d)",
- (long)mem, (long)MALLOC_BASE(mem), (long)MALLOC_SIZE(mem));
- else
- MALLOC_DEBUG (-1, "realloc: returning 0");
- return mem;
- }
|