From b35f7d482a47b0d042366fcf307b7751b3cf28a7 Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Mon, 6 Feb 2023 13:48:24 +0100 Subject: add realloc --- lib/malloc/malloc.c | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) (limited to 'lib/malloc/malloc.c') diff --git a/lib/malloc/malloc.c b/lib/malloc/malloc.c index a0e9ebf..e941c31 100644 --- a/lib/malloc/malloc.c +++ b/lib/malloc/malloc.c @@ -111,6 +111,47 @@ void free(void *ptr) } +/** DOC + * @type function + * @name realloc + * + * @param void *ptr + * @param u64 size + * @return void* + * + * @description + * Copies content of *ptr to a new location and returns new adress. + */ +void *realloc(void *ptr, u64 size) +{ + segment_t *seg = mbrk.first; + void *mem; + char *d; + + for (; seg; seg = seg->next) { + if (ptr == seg->ptr) + break; + } + + if (!seg) + return 0; + + if (seg->size == size) + return seg->ptr; + + mem = malloc(size); + d = mem; + + for (const char *p = (const char*)ptr; p < (const char*)ptr + seg->size; ++p) { + *(d++) = *p; + } + + free(ptr); + + return mem; +} + + /** DOC * @type function * @name __initialize_memory @@ -143,7 +184,7 @@ segment_t *__find_free_segment(u64 size) segment_t * seg = mbrk.first; for (; seg; seg = seg->next) { - if (seg->free && size == seg->size) + if (seg->free && seg->size == size) return seg; } @@ -171,7 +212,7 @@ segment_t *__allocate_new(u64 size) brk((void*)mbrk.current); segment_t *seg = (segment_t*)last; - seg->ptr = (void*)(mbrk.current - size); + seg->ptr = (void*)(last + sizeof(segment_t)); seg->size = size; seg->free = 0; seg->next = 0; -- cgit v1.2.3-70-g09d2