Skip to content

Commit

Permalink
Fixing realloc's behavior
Browse files Browse the repository at this point in the history
Sometimes, realloc would allocate slightly too big memory blocks.
  • Loading branch information
nicolasnoble authored Jan 9, 2024
1 parent 69e0687 commit 7c6f197
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions libc/src/malloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -116,33 +116,33 @@ void * base_realloc(void * ptr, size_t size) {
if (!ptr)
return malloc(size);

size = (size + sizeof(heap_t) + 7) & ~7;
size_t block_size = (size + sizeof(heap_t) + 7) & ~7;

prev = (heap_t *) ((uintptr_t) ptr - sizeof(heap_t));

// New memory block shorter ?
if (prev->size >= size) {
prev->size = size;
if (prev->size >= block_size) {
prev->size = block_size;
if (!prev->next)
sbrk(ptr + size - sbrk(0));
sbrk(ptr + block_size - sbrk(0));

return ptr;
}

// New memory block larger
// Is it the last one ?
if (!prev->next) {
new = sbrk(size - prev->size);
new = sbrk(block_size - prev->size);
if (!new)
return NULL;

prev->size = size;
prev->size = block_size;
return ptr;
}

// Do we have free memory after it ?
if ((prev->next->ptr - ptr) > size) {
prev->size = size;
if ((prev->next->ptr - ptr) > block_size) {
prev->size = block_size;
return ptr;
}

Expand Down

0 comments on commit 7c6f197

Please sign in to comment.