This commit is contained in:
Gregory 2019-04-26 22:18:34 +03:00
parent fc088b2fa0
commit 863d913ce3
3 changed files with 54 additions and 7 deletions

View file

@ -4,14 +4,19 @@
# include <stddef.h> # include <stddef.h>
# include <stdint.h> # include <stdint.h>
# define MIN_ALLOC_UNITS 100
typedef struct s_header typedef struct s_header
{ {
struct s_header *next; struct s_header *next;
size_t units; size_t units;
} t_header; } t_header;
# define UINIT (sizeof(t_header))
static t_header base; static t_header base;
static t_header *freep = NULL; static t_header *free_blocks = NULL;
void free(void *ptr); void free(void *ptr);
void *malloc(size_t size); void *malloc(size_t size);

29
src/free.c Normal file
View file

@ -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;
}

View file

@ -1,9 +1,17 @@
#include "ft_malloc.h" #include "ft_malloc.h"
#include <sys/mman.h>
t_header *morecore(size_t size) t_header *morecore(size_t nuints)
{ {
(void)size; t_header *block;
return NULL; 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) void *malloc(size_t size)
@ -14,10 +22,10 @@ void *malloc(size_t size)
void *space; void *space;
space = NULL; space = NULL;
nunits = (size + sizeof(t_header) - 1) / (sizeof(t_header) + 1); nunits = (size + UINIT - 1) / (UINIT + 1);
if ((prev = freep) == NULL) if ((prev = free_blocks) == NULL)
{ {
base.next = freep = prev = &base; base.next = free_blocks = prev = &base;
base.units = 0; base.units = 0;
} }
while(!space) while(!space)
@ -34,6 +42,11 @@ void *malloc(size_t size)
curr->units = nunits; curr->units = nunits;
} }
} }
free_blocks = prev;
space = (void *)(curr + UINIT);
if (curr == free_blocks)
if ((curr = morecore(nunits)) == NULL)
return (NULL);
prev = curr; prev = curr;
curr = curr->next; curr = curr->next;
} }