From 5aba0ff0c34fcd9a8fb91f78ee3587a23e6f8a9f Mon Sep 17 00:00:00 2001 From: Guillem George Date: Thu, 6 Nov 2025 19:56:55 +0100 Subject: [PATCH] backup --- malloc/src/helpers/helpers.c | 25 +++++++++++++++++++++++++ malloc/src/helpers/helpers.h | 16 ++++++++++++++-- malloc/src/malloc.c | 11 +++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/malloc/src/helpers/helpers.c b/malloc/src/helpers/helpers.c index 52db459..928234e 100644 --- a/malloc/src/helpers/helpers.c +++ b/malloc/src/helpers/helpers.c @@ -1,5 +1,6 @@ #include "helpers.h" +#include #include // Returns the smallest power of 2 greater or equal to s @@ -55,7 +56,31 @@ void *find_free_block(struct bucket *buck) struct bucket *create_bucket(size_t min_alloc_size) { + // Round up size_t alloc_size = s2p(min_alloc_size); + // Get page void *page = mmap(NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, -1, 0); + + if (page == NULL) + return NULL; + + // Init bucket + struct bucket *header = page; + header->page = page + sizeof(struct bucket); + header->block_size = alloc_size; + memset(header->free_list, 0, FREE_LIST_SIZE); + + return header; +} + +struct bucket *get_free_bucket(struct bucket *head, size_t size) +{ + while (head != NULL) + { + if (head->block_size >= size) + return head; + } + + return NULL; } diff --git a/malloc/src/helpers/helpers.h b/malloc/src/helpers/helpers.h index 51477f5..c6c622c 100644 --- a/malloc/src/helpers/helpers.h +++ b/malloc/src/helpers/helpers.h @@ -1,18 +1,30 @@ #ifndef HELPERS_H #define HELPERS_H +// #define PAGE_SIZE (size_t) sysconf(_SC_PAGE_SIZE) +#define PAGE_SIZE 4096 +#define MIN_BLOCK_SIZE 8 +#define FREE_LIST_SIZE PAGE_SIZE / MIN_BLOCK_SIZE / sizeof(unsigned char) + #include +// Header +// Contains all informations about the concerned bucket struct bucket { unsigned block_size; - unsigned char free_list[64]; // 4096 / MIN_BLOCK_SIZE / - // sizeof(unsigned char) (in bits) + unsigned char free_list[FREE_LIST_SIZE]; // 4096 / MIN_BLOCK_SIZE / + // sizeof(unsigned char) char *page; + + struct bucket *next; + + size_t checksum; }; size_t get_next_2power(size_t n); void *find_free_block(struct bucket *buck); struct bucket *create_bucket(size_t min_alloc_size); +struct bucket *get_free_bucket(struct bucket *head, size_t size); #endif // ! HELPERS_H diff --git a/malloc/src/malloc.c b/malloc/src/malloc.c index 26e8ab1..4419fdb 100644 --- a/malloc/src/malloc.c +++ b/malloc/src/malloc.c @@ -1,9 +1,20 @@ #include +#include "helpers/helpers.h" + +struct bucket *head = NULL; + __attribute__((visibility("default"))) void *malloc(size_t size) { if (size == 0) return NULL; + + struct bucket *buck = get_free_bucket(head, size); + if (buck == NULL) + { + buck = create_bucket(size); + return ...; + } } __attribute__((visibility("default"))) void free(void *ptr)