fix: write correctly prev and next block on deletion

This commit is contained in:
starnakin 2024-07-30 11:33:42 +02:00
parent 290a120319
commit 98a5e989c2
2 changed files with 25 additions and 10 deletions

View File

@ -43,21 +43,35 @@ int chunk_split(chunk_t *chunk, chunk_t *new_chunk, size_t new_size)
void destroy_chunk(chunk_t *chunk) void destroy_chunk(chunk_t *chunk)
{ {
chunk_t chunk_next_to; chunk_t chunk_prev, chunk_next, *first_chunk = chunk, *last_chunk = chunk;
if (chunk->prev != NULL) if (chunk->prev != NULL)
{ {
chunk_read(chunk->prev, &chunk_next_to); chunk_read(chunk->prev, &chunk_prev);
if (chunk_next_to.block_id == chunk->block_id && chunk_next_to.is_used == false) if (chunk_prev.block_id == chunk->block_id && chunk_prev.is_used == false)
chunk_merge(&chunk_next_to, chunk); chunk_merge(&chunk_prev, chunk);
*chunk = chunk_next_to; first_chunk = &chunk_prev;
} }
if (chunk->next != NULL) if (chunk->next != NULL)
{ {
chunk_read(chunk->next, &chunk_next_to); chunk_read(chunk->next, &chunk_next);
if (chunk_next_to.block_id == chunk->block_id && chunk_next_to.is_used == false) if (chunk_next.block_id == chunk->block_id && chunk_next.is_used == false)
chunk_merge(chunk, &chunk_next_to); chunk_merge(chunk, &chunk_next);
last_chunk = &chunk_next;
} }
if (last_chunk != chunk)
{
last_chunk->prev = chunk->prev;
chunk_write(last_chunk);
}
chunk->is_used = false; chunk->is_used = false;
chunk_write(chunk); chunk_write(chunk);
if (first_chunk != chunk)
{
first_chunk->next = chunk->next;
chunk_write(first_chunk);
}
} }

View File

@ -33,6 +33,7 @@ int main(int ac, char **av)
test(NULL, allocs_tree[LARGE], "alloc free", "simple alloc, simple free"); test(NULL, allocs_tree[LARGE], "alloc free", "simple alloc, simple free");
ptr = ft_malloc(10000000); ptr = ft_malloc(10000000);
test(ptr, ((void **) allocs_tree[LARGE])[CHUNK_DATA_START_POS], "free alloc", "alloc after a free on the first block"); test(ptr, ((void **) allocs_tree[LARGE])[CHUNK_DATA_START_POS], "free alloc", "alloc after a free on the first block");
ft_free(ptr);
void *ptr1 = ft_malloc(10000000); void *ptr1 = ft_malloc(10000000);
void *ptr2 = ft_malloc(10000000); void *ptr2 = ft_malloc(10000000);
void *ptr3 = ft_malloc(10000000); void *ptr3 = ft_malloc(10000000);
@ -42,9 +43,9 @@ int main(int ac, char **av)
ft_free(ptr1); ft_free(ptr1);
test(NOT_NULL, raw_get_chunk(allocs_tree[LARGE], ptr2), "free disorder1", ""); test(NOT_NULL, raw_get_chunk(allocs_tree[LARGE], ptr2), "free disorder1", "");
ft_free(ptr3); ft_free(ptr3);
test(NOT_NULL, raw_get_chunk(allocs_tree[LARGE], ptr2), "free disorder1", ""); test(NOT_NULL, raw_get_chunk(allocs_tree[LARGE], ptr2), "free disorder2", "");
ft_free(ptr2); ft_free(ptr2);
test(NULL, allocs_tree[LARGE], "free disorder1", ""); test(NULL, allocs_tree[LARGE], "free disorder3", "");
return 0; return 0;
} }