42_malloc/src/free.c

82 lines
1.5 KiB
C

#include "chunk.h"
#include "malloc.h"
#include <stdbool.h>
void free_tiny(chunk_t *chunk)
{
chunk_t chunk_prev, chunk_next, *first_chunk = chunk, *last_chunk = chunk;
if (chunk->prev)
{
chunk_read(chunk->prev, &chunk_prev);
if (chunk_prev.is_used == false && chunk_prev.block_id == chunk->block_id)
first_chunk = &chunk_prev;
}
if (chunk->next)
{
chunk_read(chunk->next, &chunk_next);
if (chunk_next.is_used == false && chunk_next.block_id == chunk->block_id)
last_chunk = &chunk_next;
}
first_chunk->is_used = false;
chunk_merge(first_chunk, last_chunk);
if (is_alone_on_block(first_chunk))
{
if (first_chunk->current == allocs_tree[TINY])
allocs_tree[TINY] = last_chunk->next;
destroy_block(first_chunk);
}
}
void free_small(chunk_t *chunk)
{
(void) chunk;
}
void free_large(chunk_t *chunk)
{
if (chunk->current == allocs_tree[LARGE])
allocs_tree[LARGE] = chunk->next;
destroy_block(chunk);
}
static void (*free_funcs[3])(chunk_t*) = {free_tiny, free_small, free_large};
void ft_free(void *ptr)
{
void **root;
void *raw_chunk;
chunk_t chunk;
size_t i;
if (ptr == NULL)
return;
for (i = TINY; i <= LARGE + 1; i++)
{
#ifndef DEBUG
if (i > LARGE)
write(2, "chunk not found\n", 16);
#endif
root = allocs_tree[i];
raw_chunk = raw_get_chunk(root, ptr);
if (raw_chunk == NULL)
continue;
break;
}
chunk_read(raw_chunk, &chunk);
#ifndef DEBUG
if (chunk.is_used == false)
write(2, "double free\n", 12);
#endif
// CALL THE RIGHT FREE FUNCTION DEPEND ON SIZE
free_funcs[i](&chunk);
}