diff --git a/inc/ft_malloc.h b/inc/ft_malloc.h index 4fccf1b..162ad46 100644 --- a/inc/ft_malloc.h +++ b/inc/ft_malloc.h @@ -4,14 +4,19 @@ # include # include +# define MIN_ALLOC_UNITS 100 + typedef struct s_header { struct s_header *next; size_t units; } t_header; +# define UINIT (sizeof(t_header)) + + static t_header base; -static t_header *freep = NULL; +static t_header *free_blocks = NULL; void free(void *ptr); void *malloc(size_t size); diff --git a/src/free.c b/src/free.c new file mode 100644 index 0000000..5acc9d0 --- /dev/null +++ b/src/free.c @@ -0,0 +1,29 @@ +#include "ft_malloc.h" + +void free(void *used) +{ + t_header *runner; + t_header *to_be_freed; + + to_be_freed = (t_header *)used - UINIT; + runner = free_blocks; + while(!(to_be_freed > runner && to_be_freed < runner->next)) + { + if (runner >= runner->next && (to_be_freed > runner || to_be_freed < runner->next)) + break ; + runner = runner->next; + } + if (to_be_freed + to_be_freed->units == runner->next) + { + to_be_freed->units += runner->units; + to_be_freed->next = runner->next->next; + } + else if (runner + runner->units == to_be_freed) + { + runner->units += to_be_freed->units; + runner->next = to_be_freed->next; + } + else + runner->next = to_be_freed; + free_blocks = runner; +} diff --git a/src/malloc.c b/src/malloc.c index 31ee2f6..b6a80d4 100644 --- a/src/malloc.c +++ b/src/malloc.c @@ -1,9 +1,17 @@ #include "ft_malloc.h" +#include -t_header *morecore(size_t size) +t_header *morecore(size_t nuints) { - (void)size; - return NULL; + t_header *block; + if (nuints < MIN_ALLOC_UNITS) + nuints = MIN_ALLOC_UNITS; + block = mmap(NULL, nuints * UINIT, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0); + if (block == MAP_FAILED) + return (NULL); + block->units = nuints; + free((void *)(block + UINIT)); + return free_blocks; } void *malloc(size_t size) @@ -14,10 +22,10 @@ void *malloc(size_t size) void *space; space = NULL; - nunits = (size + sizeof(t_header) - 1) / (sizeof(t_header) + 1); - if ((prev = freep) == NULL) + nunits = (size + UINIT - 1) / (UINIT + 1); + if ((prev = free_blocks) == NULL) { - base.next = freep = prev = &base; + base.next = free_blocks = prev = &base; base.units = 0; } while(!space) @@ -34,6 +42,11 @@ void *malloc(size_t size) curr->units = nunits; } } + free_blocks = prev; + space = (void *)(curr + UINIT); + if (curr == free_blocks) + if ((curr = morecore(nunits)) == NULL) + return (NULL); prev = curr; curr = curr->next; }