From 98a5e989c2d6d268e596c42010ae94cfcbe514b5 Mon Sep 17 00:00:00 2001 From: starnakin Date: Tue, 30 Jul 2024 11:33:42 +0200 Subject: [PATCH] fix: write correctly prev and next block on deletion --- src/chunk_manager.c | 30 ++++++++++++++++++++++-------- test/main.c | 5 +++-- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/chunk_manager.c b/src/chunk_manager.c index 13df225..475cfa2 100644 --- a/src/chunk_manager.c +++ b/src/chunk_manager.c @@ -43,21 +43,35 @@ int chunk_split(chunk_t *chunk, chunk_t *new_chunk, size_t new_size) 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) { - chunk_read(chunk->prev, &chunk_next_to); - if (chunk_next_to.block_id == chunk->block_id && chunk_next_to.is_used == false) - chunk_merge(&chunk_next_to, chunk); - *chunk = chunk_next_to; + chunk_read(chunk->prev, &chunk_prev); + if (chunk_prev.block_id == chunk->block_id && chunk_prev.is_used == false) + chunk_merge(&chunk_prev, chunk); + first_chunk = &chunk_prev; } if (chunk->next != NULL) { - chunk_read(chunk->next, &chunk_next_to); - if (chunk_next_to.block_id == chunk->block_id && chunk_next_to.is_used == false) - chunk_merge(chunk, &chunk_next_to); + chunk_read(chunk->next, &chunk_next); + if (chunk_next.block_id == chunk->block_id && chunk_next.is_used == false) + 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_write(chunk); + + if (first_chunk != chunk) + { + first_chunk->next = chunk->next; + chunk_write(first_chunk); + } } \ No newline at end of file diff --git a/test/main.c b/test/main.c index a7db4cc..e683267 100644 --- a/test/main.c +++ b/test/main.c @@ -33,6 +33,7 @@ int main(int ac, char **av) test(NULL, allocs_tree[LARGE], "alloc free", "simple alloc, simple free"); ptr = ft_malloc(10000000); 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 *ptr2 = ft_malloc(10000000); void *ptr3 = ft_malloc(10000000); @@ -42,9 +43,9 @@ int main(int ac, char **av) ft_free(ptr1); test(NOT_NULL, raw_get_chunk(allocs_tree[LARGE], ptr2), "free disorder1", ""); 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); - test(NULL, allocs_tree[LARGE], "free disorder1", ""); + test(NULL, allocs_tree[LARGE], "free disorder3", ""); return 0; } \ No newline at end of file