diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2023-02-06 13:48:24 +0100 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2023-02-06 13:48:24 +0100 |
| commit | b35f7d482a47b0d042366fcf307b7751b3cf28a7 (patch) | |
| tree | ab2a181ef7d307141eee0c28f160171d2cbba4c6 /lib/malloc/malloc.c | |
| parent | 44b03ec8273676eef5681a1f5febe02dde7ed2cd (diff) | |
add realloc
Diffstat (limited to 'lib/malloc/malloc.c')
| -rw-r--r-- | lib/malloc/malloc.c | 45 |
1 files changed, 43 insertions, 2 deletions
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 @@ -113,6 +113,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 * * @description @@ -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; |