add free
This commit is contained in:
parent
fc088b2fa0
commit
863d913ce3
3 changed files with 54 additions and 7 deletions
|
@ -4,14 +4,19 @@
|
|||
# include <stddef.h>
|
||||
# include <stdint.h>
|
||||
|
||||
# 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);
|
||||
|
|
29
src/free.c
Normal file
29
src/free.c
Normal 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;
|
||||
}
|
25
src/malloc.c
25
src/malloc.c
|
@ -1,9 +1,17 @@
|
|||
#include "ft_malloc.h"
|
||||
#include <sys/mman.h>
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue